java - Comparators sorting -
i'm not comparators need learn it, i've done far keep getting error @ 'system.out.println(compy("january", "march", "october", "april"));'... please help, explanation fix. thank you!
import java.util.collections; import java.util.comparator; import java.util.list; public class months { public static void main (string args[]){ system.out.println(comp("january","may")); system.out.println(comp("october", "may")); system.out.println(comp("august","august")); system.out.println(comp("january", "march")); system.out.println(compy("january", "march", "october", "april")); } static int comp(string s1, string s2){ while (true){ int r = 0; int s = 0; if(s1.equals("january")){ r=1; } if(s1.equals("february")){ r=2; } if(s1.equals("march")){ r=3; } if(s1.equals("april")){ r=4; } if(s1.equals("may")){ r=5; } if(s1.equals("june")){ r=6; } if(s1.equals("july")){ r=7; } if(s1.equals("august")){ r=8; } if(s1.equals("september")){ r=9; } if(s1.equals("october")){ r=10; } if(s1.equals("november")){ r=11; } if(s1.equals("december")){ r=12; } if(s2.equals("january")){ s=1; } if(s2.equals("february")){ s=2; } if(s2.equals("march")){ s=3; } if(s2.equals("april")){ s=4; } if(s2.equals("may")){ s=5; } if(s2.equals("june")){ s=6; } if(s2.equals("july")){ s=7; } if(s2.equals("august")){ s=8; } if(s2.equals("september")){ s=9; } if(s2.equals("october")){ s=10; } if(s2.equals("november")){ s=11; } if(s2.equals("december")){ s=12; } if(r<s){ return -1; } if(r>s){ return 1; } if(r==s){ return 0; } } } public class comp implements comparator { public int compare(object o1, object o2){ return comp((string)o1, (string)o2); } } void sort(list l){ comparator compy = new comp(); collections.sort(l, compy); } }
this how can sort list code.
list<string> list = new arraylist<string>(); list.add("march"); list.add("january"); list.add("october"); list.add("april"); system.out.println("before sort: " + list); // prints: before sort: [march, january, october, april] new months().sort(list); // sort system.out.println("after sort: " + list); // prints: after sort: [january, march, april, october]
Comments
Post a Comment