[英]Java bluej . Get the next element from the arrayList
I am Beginner practicing java with bluej and trying to print the next element every time I use the getNext() method .我是初学者用 bluej 练习 java 并在每次使用 getNext() 方法时尝试打印下一个元素。 I tried some options but they didn't work and now I am stuck .
我尝试了一些选项,但它们不起作用,现在我被卡住了。 Here is my code:
这是我的代码:
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());
}
}
I am guessing you only want to print one question whenever getNextQuestion
is called.我猜你只想在调用
getNextQuestion
时打印一个问题。 In that case, you need to do this:在这种情况下,您需要执行以下操作:
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());
}
}
As you can see, counter
is now a global variable inside whaever class contains the method, and you don't need the iterator at all.如您所见,
counter
现在是包含该方法的类中的全局变量,您根本不需要迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.