每次循环结束时,我都会尝试打印歌曲名称和歌曲长度。我该怎么做呢? Report+= songTitles[numSongs] + songLengths[numSongs]
?
然后,我需要进行线性搜索以从播放列表中删除歌曲。我是否需要使用相同的报告字符串让用户看到所有歌曲?我只需要帮助。谢谢。
import javax.swing.JOptionPane;
public class asdf_Playlist {
public static void main(String[] args) {
final int MAX_SONGS = 106;
int totalDuration = 0;
int numSongs = 0;
boolean exitVar = false;
int i = 0;
String[] songTitles = new String[MAX_SONGS];
int[] songLengths = new int[MAX_SONGS];
while (exitVar == false && numSongs <= songTitles.length) {
do {
songTitles[numSongs] = JOptionPane.showInputDialog(null,"Enter a song name, or type -1 to exit");
if (songTitles[numSongs].equals("")) {
JOptionPane.showMessageDialog(null,"Error: Please enter a valid song name, or type -1 to exit");
} else if (songTitles[numSongs].equals("-1")) {
exitVar = true;
}
} while (songTitles[numSongs].equals(""));
do {
try {
songLengths[numSongs] = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a song length, e.g. 4."));
if (songLengths[numSongs] > 0) {
totalDuration += songLengths[numSongs];
} else {
songLengths[numSongs] = -1;
JOptionPane.showMessageDialog(null,"Error: please enter a valid song length, e.g. 4.");
}
} catch (NumberFormatException e) {
songLengths[numSongs] = -1;
JOptionPane.showMessageDialog(null, "Error: please enter a valid song length, e.g. 4.");
}
} while (songLengths[numSongs] <= 0);
boolean addMore = true;
while ((numSongs <= MAX_SONGS) && (addMore == true)) {
JOptionPane.showMessageDialog(null, "Song #" + (i+1) + ": " + songTitles[i] + " length: " + songLengths[i] + "\n");
i++;
if (songTitles[i] == null) {
addMore = false;
}
}
numSongs++;
}
}
}
答案 0 :(得分:0)
我有一些建议让你更容易。
首先,您应该创建一个类来捕获歌曲信息,而不是拥有两个单独的数组。从长远来看,这将使您的生活更加轻松(并且是更好的OO练习)。然后,您可以创建toString
方法作为该类的一部分来格式化歌曲信息:
class Song {
private final String title;
private final int length;
public String toString() {
return title + ":" + length;
}
}
您的歌曲阵列会变得更简单:
private Song[] songs = new Song[MAX_SONGS];
打印整个列表可以通过多种方式完成。在Java 8之前,它通常看起来像:
for (Song song: songs)
System.out.println(song);
自Java 8发布以来,这可以简化为:
Arrays.stream(songs).forEach(System.out::println);
从数组中删除项目并不像从集合中删除它们那么容易。但它仍然不太难:
Song[] copy = new Song[MAX_SONGS];
int copiedSongs = 0;
for (Song song: songs)
if (/* condition for copying */)
copy[copiedSongs++] = song;
songs = copy;
numSongs = copiedSongs;
同样,使用Java 8,这变得更加简单:
songs = Arrays.stream(songs).filter(/*condition*/).toArray();
numSongs = songs.length;