使用Collections.sort()对MP3列表进行排序

时间:2011-05-28 16:13:11

标签: java sorting compareto

我正在使用Collections.sort()按运行时顺序对MP3列表进行排序,如果运行时相等,则按标题按字母顺序排序,如果标题相等,则按作曲家排序。我将输入输入stdin

示例输入

3
&
Pink Frost&Phillipps, Martin&234933
Se quel guerrier io fossi&Puccini, Giacomo&297539
Non 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));
}
}

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

2 个答案:

答案 0 :(得分:3)

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

String[] fields = line.split(sep);

答案 1 :(得分: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]));
}
如果有EOF(ctrl-z或ctrl-d取决于平台),

readline仅给出null

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