Java bluej .从 arrayList 中获取下一个元素

标签 java arraylist iterator bluej

我是初学者,正在使用 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/

相关文章:

java - 使用接口(interface)用对象填充列表

c++ - 无法将元素插入嵌套的 STL 整数集中

java - 类和迭代器接口(interface)之间的关系

java - 从 Android 中的请求 PHP 获取响应

java - 确定文本文件长度的最有效方法是什么?

java - 循环下拉网络驱动程序

java - ArrayList 元素不被打印

Java-比较 itr() 和 itr.next() 的 double 值

java - 如何在 Java jdb 中跳过断点一定次数?

java - 如何用不同类的对象填充数组?详情如下