Java bluej . Get the next element from the arrayList

georgi dimitrov :

I am Beginner practicing java with bluej and trying to print the next element every time I use the getNext() method . 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());


    }
}
Schred :

I am guessing you only want to print one question whenever getNextQuestion is called. 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=349574&siteId=1