[练习]IO模块的练习

要求:

        描述一个学生类,学生类包含学生姓名,数学成绩,语文成绩,英语成绩等属性,从键盘输入学生对象,然后将输入的学生对象存入文件,按照总分的大小从大到小排序。

import java.io.*;
import java.util.*;

//描述学生类
class Student implements Comparable<Student>
{
	private String name;
	private int math;
	private int china;
	private int english;
	private int sum;

	public Student(String name, int math, int china, int english){
		this.name = name;
		this.math = math;
		this.china = china;
		this.english = english;
		sum = math + china + english;
	}

	//实现Comparable接口,实现改方法
	public int compareTo(Student s){
		int num = Integer.valueOf(this.sum).compareTo(Integer.valueOf(s.sum));
		if(num == 0){
			return this.name.compareTo(s.name);
		}
		return num;
	} 

	public String toString(){
		return this.name + " : [" + this.math + "," + this.china + "," + this.english + "]";
	}

	public int getSum(){
		return this.sum;
	}
}

class StudentUtil
{
	private static Set<Student> s;
	public StudentUtil(Set<Student> s){
		this.s = s;
	}
	//以“姓名,数学成绩,语文成绩,英语成绩”的形式从键盘存入数据
	public static void getStudent() throws Exception{
		BufferedReader bis = new BufferedReader(new InputStreamReader(System.in)); 
		String str = null;
		while((str = bis.readLine()) != null){
			if(str.equals("over")){
				break;
			}
			String[] info = str.split(",");
			Student student = new Student(info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2]), Integer.parseInt(info[3]));
			s.add(student);
		}
		bis.close();
	}

	//将集合中数据写入文件
	public void writeStudent() throws Exception{
		BufferedWriter bw = new BufferedWriter(new FileWriter("StuInfo.txt"));
		Iterator iterator = s.iterator();
		while(iterator.hasNext()){
			Student s = (Student)iterator.next();
			bw.write(s.toString() + "\t");
			bw.write(s.getSum()+"");
			bw.newLine();
			bw.flush();
		}

		bw.close();
	}
}


class StudentDemo 
{
	public static void main(String[] args) throws Exception
	{
		//获得从逆向排序的比较器
		Comparator<Student> c = Collections.reverseOrder();
		StudentUtil su = new StudentUtil(new TreeSet<Student>(c));
		su.getStudent();
		System.out.println("获取成功!");
		su.writeStudent();
		System.out.println("写入成功!");
	}
}


 

发布了36 篇原创文章 · 获赞 3 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章