繁体   English   中英

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

[英]Using Collections.sort() to sort a list of MP3s

我正在使用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));
}
}

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

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

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

你的时间有问题

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM