简体   繁体   中英

arraylist loop not displaying

I need to make a program that let's you add CD titles, remove them etc.

I need to use an Arraylist for my program (to store the songs)

Code:

    ArrayList songlist = new ArrayList();
    Collections.addAll(songlist, "Something", "Hard Days Night", "I am the Walrus", "Yesterday", "All the Lonely People");
    Collections.sort(songlist);

    int songlistsize = songlist.size ();
    for (int i = 0; i < songlistsize; i++) {
        outputField.setText(i + ": " + songlist.get(i));

The problem is that the program will only display "Yesterday", and not anything else.

outputField.setText(i + ": " + songlist.get(i));

Because you are setting the last value and not appending. Do something like this:

    StringBuilder string = new StringBuilder();
    for (int i = 0; i < songlistsize; i++) {
            string.append(songlist.get(i));
    }
    outputField.setText(string);

There are many other problems with the code but I am sticking to the point.

If you try to print your output on the console you will see that the part that deals with the collection works fine. But since setText() replaces the current String with the latest song name you only see "Yesterday" because its at the end of your collection. That´s why you should try to append() the next song name to your String or make sure you copy your current String, add the next item and finally use setText()

For example:

String string = "";
for (int i = 0; i < songlistsize; i++) 
{
        string = outputField.getText() + songlist.get(i);
        outputField.setText(string);
}

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