I'm using Collections.sort()
to sort a list of MP3s in order of runtime, and if runtime is equal, then sort alphabetically by title, and if title is equal then sort by composer. I put the input into stdin
i.e.
Example Input
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
But then it doesn't come up with anything via the input. I am confused since it should work perfectly. I don't get any errors.
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));
}
}
If someone could point me in the right direction, that would make me grateful.
String[] fields = sep.split(line);
seems wrong - you're not trying to split the separator string on the song input; you want to split the song input on the separator:
String[] fields = line.split(sep);
your while is faulty
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 only gives null on if there is a EOF (ctrl-z or ctrl-d depending on the platform)
otherwise it just blocks waiting on the next line
精彩评论