簡體   English   中英

爪哇藍。 從 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現在是包含該方法的類中的全局變量,您根本不需要迭代器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM