黑马程序员技术交流社区
标题:
关于重写sort方法遇到的问题
[打印本页]
作者:
当我遇上你
时间:
2015-1-10 14:06
标题:
关于重写sort方法遇到的问题
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;
}
}
}
复制代码
代码还没有调试,不知道写的比较方法是否真确,错误提示出现在我调用比较方法的那一行,我做了标记
作者:
kerner
时间:
2015-1-10 15:54
因为Mycompatator为内部类,而你在静态方法中调用了内部类,所以要么内部类变为静态类 static Mycomparator,要么先new Student().new Mycomparator()。
还有你的程序判断读取完毕时错误的,应该这样写:
if(!str.equals(""))
{
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);
}
else{
break;
}
复制代码
作者:
当我遇上你
时间:
2015-1-10 19:46
kerner 发表于 2015-1-10 15:54
因为Mycompatator为内部类,而你在静态方法中调用了内部类,所以要么内部类变为静态类 static Mycomparator ...
恩恩,后来我弄懂了,不过还是谢谢你解释 的那么详细
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2