[英]How to find the number of a specific element in an arraylist in Java (blueJ)
[英]Java bluej . Get the next element from the arrayList
我是初學者用 bluej 練習 java 並在每次使用 getNext() 方法時嘗試打印下一個元素。 我嘗試了一些選項,但它們不起作用,現在我被卡住了。 這是我的代碼:
public void getNextQuestion()
{
int counter = 0;
Iterator<Questions> it = this.questions.iterator();
while(it.hasNext())
{
counter = counter + 1;
Questions nextObject = it.next();
System.out.println(counter+ ". " + nextObject.getDescription());
}
}
我猜你只想在調用getNextQuestion
時打印一個問題。 在這種情況下,您需要執行以下操作:
public class MyClass {
int counter = 0;
public void getNextQuestion()
{
Questions nextObject = questions.get(counter);
counter = counter + 1;
// If counter gets to the end of the list, start from the beginning.
if(counter >= questions.size())
counter = 0;
System.out.println(counter+ ". " + nextObject.getDescription());
}
}
如您所見, counter
現在是包含該方法的類中的全局變量,您根本不需要迭代器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.