我是初学者,正在使用 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
现在是包含该方法的类中的全局变量,并且您根本不需要迭代器。
关于Java bluej .从 arrayList 中获取下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60803786/