有人可以找出为什么在删除找到的值之后,输出包含删除之前的所有信息吗?
// 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 :(得分:0)
titles
和totalDuration
中的所有元素初始化 songTitles
和songLengths
个字符串。
如果您在search
中找到songTitles
,则会将其从songTitles
中移除,但您不会更新songTitles
。而是从songTitles追加更多歌曲。
您可能希望清除songTitles
和songLengths
并重新创建它们,在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 = "";