简体   繁体   中英

Why does for readelements() fro loop not print out?

So I've been stuck trying to get my array list to print out in the right order but it keeps printing the original input i inserted backwards for some reason, i've tried reading the array in reverse order but it doesn't work either.

public static void Add()
{
    System.out.println("You may now enter your virtual diary entry...");
    System.out.println("You may END the program at any time by typing in endp...\n");
    boolean loop = true; 
    while(loop)
    {
        String Stop = Cons.nextLine();

        if (Stop.equals("endp")| Stop.equals(""))
        {
            readelements();
            break;  
        } else {
            for (int i =0 ; i <= Notes.size(); ) {

                Notes.add(i, Stop); 
                i++;
                break; 
            }
        }
    }
} 

public static void readelements()

{

    if (Empty()) {

        Empty();
    }
    for(int i =0; i < Notes.size(); i++) {
        System.out.println(i + " = " + Notes.get(i).toString());
        Notes.toString();
    }   
}

In your else block, you break after one iteration (when i = 0) so you're always running Notes.add(0, Stop). This prepends Stop to Notes, so Notes will be in reverse order. Removing the break will cause you to insert duplicate elements into Notes (note that you're looping but always inserting Stop). Try changing your entire else block to just Notes.add(Stop); . This will add the current value of Stop to the end of Notes and should fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM