0

I first created an arraylist in another part of the program, then used for loops to put it in the text area. Now, I want to take input from the text field, add that to the arraylist, and display the entire array, including the new element added. I tried using a for loop again, but when i click "add" while running, the program just freezes and nothing happens. Any suggestions? Thanks.

private void btnDisplayActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // Using a for loop to display unsorted list, sorting the list, then using a for loop again to display the sorted list 

    String strUnsortedList = "";
    for(int i = 0; i < strCDNames.size(); i++)  {
         strUnsortedList += strCDNames.get(i) + "\n";

    }

    Collections.sort(strCDNames);

    String strSortedList = "";
    for(int i = 0; i < strCDNames.size(); i++)  {
         strSortedList += strCDNames.get(i) + "\n";

    }
    txtOutput.setText("Unsorted Order: \n" + strUnsortedList + "\nSorted Order: \n" + strSortedList);



}                                          

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String strAddedList = "";
    for (int i = 0; i < strCDNames.size(); i++)  {
          strAddedList += strCDNames.add(txtInputTitleArtist.getText());
    }
    txtOutput.setText(" " + strAddedList);
}                           
1
  • i wil always be less than strCDNames Commented Jul 20, 2015 at 20:07

2 Answers 2

2
for (int i = 0; i < strCDNames.size(); i++)  {
    strAddedList += strCDNames.add(txtInputTitleArtist.getText());
}

This is an infinite loop. You keep adding to the list, which means that the list size will keep increasing. Hence i will always be lesser than strCDNames.size().

Instead you can do something like this:

strCDNames.add(txtInputTitleArtist.getText());
String strAddedList = String.join(" ", strCDNames);
Sign up to request clarification or add additional context in comments.

Comments

0

Vivin is right. I just want to add that the arraylist add method returns a boolean (https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-E-). So, in this case strAddedList wouldn't even be properly updated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.