0

Collections.sort()用来按运行时顺序对 MP3 列表进行排序,如果运行时相等,则按标题字母顺序排序,如果标题相等,则按作曲家排序。我把输入放到stdinie

示例输入

3
&
Pink Frost&Phillipps, Martin&234933
继续游击队 io fossi&Puccini, Giacomo&297539
非 piu andrai&Mozart&234933
M'appari tutt'amor&Flotow, F&252905

但随后它并没有通过输入提供任何东西。我很困惑,因为它应该可以完美运行。我没有收到任何错误。

public class Lab3Algorithm {

public static void main(String args[]) throws IOException {

    List<Song> songs = new ArrayList<Song>();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int numOfSongsRequired = Integer.parseInt(br.readLine());
    String sep = br.readLine();

    String line;
    while((line = br.readLine()) != null) {
        String[] fields = sep.split(line);
        songs.add(new Song(fields[0], fields[1], fields[2]));
    }
    Collections.sort(songs);

    System.out.println(songs);
}

}

public class Song implements Comparable<Song> {

private final String title;
private final String composer;
private final int runningTime;

public Song(String title, String composer, String runningTime) {
    this.title = title;
    this.composer = composer;
    this.runningTime = Integer.parseInt(runningTime);
}

public String getTitle(){
    return this.title;
}

public String getComposer(){
    return this.composer;
}

public int getRunningTime(){
    return this.runningTime;
}

@Override
public int compareTo(Song s) {
    if (runningTime > s.runningTime) {
        return 1;
    } else if (runningTime < s.runningTime) {
        return -1;
    }
    int lastCmp = title.compareTo(s.title);
    return (lastCmp != 0 ? lastCmp : composer.compareTo(s.composer));
}
}

如果有人能指出我正确的方向,那将让我感激不尽。

4

2 回答 2

3

String[] fields = sep.split(line);似乎错了-您没有尝试在歌曲输入上拆分分隔符字符串;你想在分隔符上分割歌曲输入:

String[] fields = line.split(sep);
于 2011-05-28T16:20:04.150 回答
2

你的时间有问题

for(int i = 0;i<numOfSongsRequired ;i++) {
    line = br.readLine();
    String[] fields = line.split(sep);//line should be splitted by sep btw
    songs.add(new Song(fields[0], fields[1], fields[2]));
}

readline 仅在存在 EOF 时才给出 null (ctrl-z 或 ctrl-d 取决于平台)

否则它只会阻止在下一行等待

于 2011-05-28T16:20:06.743 回答