谁能弄清楚为什么删除找到的值后,输出中包含删除之前的所有信息?

  // Prints current items in both arrays
  String titles = "";
  String lengths = "";
  for (int i = 0; i < numOfSongs; i++) {
     titles += songTitles[i] + " ";
     lengths += songLengths[i] + " ";
  }
  JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);
  // Determines if the user wants to remove a song from the current list
        boolean found = false;
        // If search matches a song in array, set title to null and length to 0
        for (int i = 0; i < songTitles.length; i++) {
           if (search.equalsIgnoreCase(songTitles[i])) {
              found = true;
              songTitles[i] = null;
              songLengths[i] = 0;
           }
        }
        // Update arrays, song count, and duration across all songs
        if (found) {
           titles += songTitles[numOfSongs] + " ";
           lengths += songLengths[numOfSongs] + " ";
           totalDuration -= songLengths[numOfSongs];
           numOfSongs--;
        }
        // Print updated playlist
        JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);

最佳答案

titlestotalDuration字符串用songTitlessongLengths中的所有元素初始化。

如果在search中找到songTitles,则将其从songTitles删除,但不会更新songTitles。相反,您可以从songTitles附加更多歌曲标题。

您可能想清除songTitlessongLengths并跳过songTitles中的空值来重新创建它们。例如。

titles = "";
lengths = "";
for (int i = 0; i < numOfSongs; i++) {
    if (songTitles[i] != null) {
        titles += songTitles[i] + " ";
        lengths += songLengths[i] + " ";
    }
}


还可以考虑像这样创建字符串(Java 8)

String titles = String.join(" ", songTitles);
String lengths = String.join(" ", songLengths);

关于java - 更新的输出与旧的输出并置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33551301/

10-12 01:17