Super_Scholar
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Scanner;
public class Student
{
double chinese;
double math;
double english;
double sum;
String sname;
public Student ( double chinese, double math, double english, double sum, String sname )
{
this.chinese = chinese;
this.math = math;
this.english = english;
this.sum = sum;
this.sname = sname;
}
@Override
public String toString ()
{
return String.format ("%s\t\t%2$.1f\t\t\t%3$.1f\t\t\t%4$.1f\t\t\t%5$.1f", sname, chinese, math, english, sum);
}
public static void main ( String[] args )
{
Scanner scanner = new Scanner (System.in);
LinkedList<Student> list = new LinkedList<Student> ();
System.out.println ("从键盘输入学生的信息,输入格式为:name,30,30,30(姓名,三门课成绩)<直接回车结束>");
while (scanner.hasNextLine ())
{
String line = scanner.nextLine ().trim ();
if ("".equals (line))
{
break;
}
String[] info = line.split ("\\,");
String name = info[0];
double chinese = 0;
double math = 0;
double english = 0;
double sum = 0;
try
{
chinese = Double.parseDouble (info[1]);
math = Double.parseDouble (info[2]);
english = Double.parseDouble (info[3]);
sum = chinese + math + english;
}
catch (Exception e)
{
System.out.println ("格式不正确,重写输入:");
continue;
}
Student student = new Student (chinese, math, english, sum, name);
list.add (student);
}
scanner.close ();
Collections.sort (list, new Comparator<Student> ()
{
@Override
public int compare ( Student o1, Student o2 )
{
if (o1.sum > o2.sum)
{
return -1;
}
else if (o1.sum < o2.sum)
{
return 1;
}
else
{
return 0;
}
}
});
try
{
String file = "stu.txt";
String line = System.getProperty ("line.separator");
FileWriter fw = new FileWriter (file, true);
FileReader fr = new FileReader (file);
if (fr.read () == -1)
{
fw.write ("姓名\t\t语文\t\t数学\t\t英语\t\t总分" + line);
}
fr.close ();
for ( Student student : list )
{
fw.write (student.toString () + line);
fw.flush ();
}
fw.close ();
System.out.println ("加入完毕.");
}
catch (IOException e)
{}
}
}