Java 蓝杰。从 arrayList 中获取下一个元素

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 现在是一个全局变量,只要 class 包含该方法,您根本不需要迭代器。