更新的输出与旧输出

时间:2015-11-05 17:41:53

标签: java

有人可以找出为什么在删除找到的值之后,输出包含删除之前的所有信息吗?

  // 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); 

2 个答案:

答案 0 :(得分:0)

使用titlestotalDuration中的所有元素初始化

songTitlessongLengths个字符串。

如果您在search中找到songTitles,则会将其从songTitles中移除,但您不会更新songTitles。而是从songTitles追加更多歌曲。

您可能希望清除songTitlessongLengths并重新创建它们,在songTitles中跳过空值。 E.g。

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);

答案 1 :(得分:0)

以下语句导致与旧值连接。

titles += songTitles[numOfSongs] + " ";
lengths += songLengths[numOfSongs] + " ";

首先应通过在添加新值之前将字符串设置为空来清除现有值。

titles = "";
lengths = "";