我是使用 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
现在是包含该方法的类中的全局变量,您根本不需要迭代器。
问题的定义是什么?“代码不起作用”是什么意思?有什么错误吗?没有输出?输出错误?
我觉得不错。到底什么不起作用?this.questions 字段是什么,您是如何填写的?看起来可疑的是您使用 Iterator 而不是 Iterator,或者这只是一个拼写错误?
您的方法可能会打印所有问题,而不仅仅是下一个问题,因为您使用了“while”循环。
@Alex 我有两个类:一个是问题,另一个是测试,我将创建的对象问题放入测试列表中。我写下我尝试了很多选项来完成这项任务,但它们没有用,但我的代码运行良好
@Alex 是的,确实如此。但我不知道如何一张一张打印