- /*
- *3. 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
- * 输入格式为:name,30,30,30(姓名,三门课成绩),然后把输入的学生信息按总分从高到低的顺序
- * 写入到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观,打开这个文件,就可
- * 以很清楚的看到学生的信息。
- *
- *
- * 思路:
- * 1.从键盘读取数据,将读到的每行数据写入数组
- * 2.将数组内容作为构造函数参数传入,创建Student对象
- * 3.将创建的Student对象传入TreeSet集合进行排序
- * 4.遍历TreeSet集合将内容取出存入stu.txt文件中
- */
- import java.io.*;
- import java.util.*;
- import static java.lang.Integer.parseInt;
- class Student implements Comparable<Student>
- {
- private String name;
- private int chinese;
- private int math;
- private int english;
- public String getName()
- {
- return name;
- }
- public int getChinese()
- {
- return chinese;
- }
- public int getMath()
- {
- return math;
- }
- public int getEnglish()
- {
- return english;
- }
- public Student(String name, int chinese, int math, int english)
- {
- this.math = math;
- this.chinese = chinese;
- this.english = english;
- this.name = name;
- }
- @Override
- public int compareTo(Student o)
- {
- int th = this.chinese + this.english + this.math;
- int oo = o.chinese + o.english + o.math;
- if (th < oo)
- {
- return 1;
- }
- else if(th>oo)
- {
- return -1;
- }
- else
- {
- return this.name.compareTo(o.name);
- }
- }
- }
- public class StudentTest
- {
- public static void main(String[] args)
- {
- // 从键盘读取数据
- BufferedReader bd = new BufferedReader(new InputStreamReader(System.in));
- BufferedWriter bw = null;
- try
- {
- bw = new BufferedWriter(new FileWriter("d:\\stu.txt"));
- bw.write("姓名" + "\t" + "语文" + "\t" + "数学" + "\t" + "英语" + "\t"
- + "总分");
- bw.newLine();
- } catch (IOException e1)
- {
- e1.printStackTrace();
- }
- String line = null;
- String[] str = null;
- TreeSet<Student> ts = new TreeSet<Student>();
- System.out.println("请按照\"姓名,语文,数学,英语\"的顺序输入成绩:");
- try
- {
- while ((line = bd.readLine()) != null)
- {
- if ("over".equals(line))
- {
- break;
- }
- System.out.println("请按照\"姓名,语文,数学,英语\"的顺序输入成绩:");
- str = line.split(",");
- Student stu = new Student(str[0], parseInt(str[1]),
- parseInt(str[1]), parseInt(str[1]));
- ts.add(stu);
- }
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- Iterator<Student> it = ts.iterator();
- while (it.hasNext())
- {
- Student sd = it.next();
- int zf = sd.getChinese() + sd.getEnglish() + sd.getMath();
- // System.out.println(sd.getName() + "\t" + sd.getChinese() + "\t"+ sd.getMath() + "\t" + sd.getEnglish() + "\t" + zf);
- try
- {
- bw.write(sd.getName() + "\t" + sd.getChinese() + "\t"+ sd.getMath() + "\t" + sd.getEnglish() + "\t" + zf);
- bw.newLine();
- bw.flush();
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- try
- {
- bd.close();
- bw.close();
- } catch (IOException e)
- {
- // FLY 自动生成的 catch 块
- e.printStackTrace();
- }
- }
- }
复制代码
共同学习,共同进步 |