0
Scanner scan = new Scanner(System.in);
        System.out.println("Enter the names of each song in the DJ's playlist: ");
        System.out.println("When finished, enter done.");
        ArrayList <String> NamesOfSongs = new ArrayList<>();
        boolean loop = true;
        while(loop)
        {
            String input = scan.nextLine();
            if (input.equals("done"))
            {
                break;
            }
            else
            {

                NamesOfSongs.add(scan.nextLine());
            }
        }
        System.out.println(NamesOfSongs);
        }

Input strings need to be added to the ArrayList until user enters "done" and the method is finished.

Results in: (after I enter 3 strings and done TWICE)

Enter the names of each song in the DJ's playlist:
When finished, enter done.
jjjj
kkkkk
iiii
done
done
[kkkkk, done]

1 Answers1

0

To compare String, you have to use equals method. For exemple input.equals("done"). This method returns true if the String"s" are equals.

In the else code, you must not use NamesOfSongs.add(scan.nextLine()); because you ask the user to enter a new value. You want to retrieve the value already entered So, use NamesOfSongs.add(input);

And, to display the contents of the ArraysList you can use a loop 'for'

    /* Print the song*/
    for(int i = 0; i < NamesOfSongs.size(); i++) {
        System.out.println(NamesOfSongs.get(i));
    }

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the names of each song in the DJ's playlist: ");
    System.out.println("When finished, enter done.");
    ArrayList <String> NamesOfSongs = new ArrayList<>();
    boolean loop = true;

    while(loop) {
        String input = scan.nextLine();
        if(input.equals("done")) {
            /* Stop the input => stop while loop*/
            loop = false; 
        } else {
            /* add song */
            NamesOfSongs.add(input);
        }
    }

    /* Print the song*/
    for(int i = 0; i < NamesOfSongs.size(); i++) {
        System.out.println(NamesOfSongs.get(i));
    }
}
Adri
  • 144
  • 8