- public static class Student
- {
- double chinese;
- double math;
- double english;
- double sum;
- String name;
- public Student(double chinese, double math, double english, double sum,
- String name)
- {
- this.chinese = chinese;
- this.math = math;
- this.english = english;
- this.sum = sum;
- this.name = name;
- }
- @Override
- public String toString()
- {
- return String.format("%s\t\t%2$.1f\t\t%3$.1f\t\t%4.1f\t\t%5$.1f", name,chinese,math,english,sum);
- }
- public static void main(String[] args)throws Exception
- {
- Scanner scanner = new Scanner(System.in);
- LinkedList<Student> linkedList = new LinkedList<Student>();
- System.out.println("请按以下格式录入学生信息:name,30,30,30(姓名,语文,数学,外语)<按回车键结束>:");
- while(scanner.hasNextLine())
- {
- String str = scanner.nextLine();
- if(!str.equals(null))
- {
- String[] inf=str.split("\\,");
- String name=inf[0];
- double chinese=Double.parseDouble(inf[1]);
- double math=Double.parseDouble(inf[2]);
- double english=Double.parseDouble(inf[3]);
- double sum=chinese+math+english;
- Student student = new Student(chinese, math, english, sum, name);
- linkedList.add(student);
- }
- }
- scanner.close();
- Collections.sort(linkedList, new MyComparator()); \\ <<----------------
- System.setOut(new PrintStream("stu.txt"));
- System.out.println("姓名\t\t语文\t\t数学\t\t外语\t\t总分");
- for(Student stu:linkedList)
- {
- System.out.println(stu.toString());
- }
- }
-
- class MyComparator implements Comparator<Student>
- {
- @Override
- public int compare(Student s1,Student s2)
- {
- if (s1.sum>s2.sum)
- {
- return (int) (s1.sum-s2.sum);
- } else if(s1.sum-s2.sum<0)
- {
- return (int) (s1.sum-s2.sum);
- }
- else return 0;
-
- }
- }
- }
复制代码
代码还没有调试,不知道写的比较方法是否真确,错误提示出现在我调用比较方法的那一行,我做了标记 |
|