我是使用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());
}
}
答案 0 :(得分:0)
我猜您只想在调用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
现在是一个包含该方法的全局变量,而您根本不需要迭代器。