2015-11-05 47 views
1

任何人都可以找出爲什麼刪除找到的值後,輸出包含刪除前的所有信息?更新後的輸出與舊輸出連接

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

我不完全確定我理解你的問題 - 看起來你的問題是由於在你的代碼開始時使用「+ =」連接你的標題和長度引起的。然後,您執行「找到的檢查」,您可以繼續將數據添加到相同的變量,而不必通過執行類似titles =「」和lengths =「」的操作來重置變量 – Brad

回答

0

titlestotalDuration字符串初始化與songTitlessongLengths所有元素。

如果您發現searchsongTitles您從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); 
0

下面的語句是導致舊值,從而將。

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

您應該首先在添加新值之前通過將字符串設置爲空來清除現有值。

titles = ""; 
lengths = "";