IO流:将键盘录入的学生成绩进行排序写入文件中

【需求】:

有五个学生,每个学生有三门课的成绩
从键盘输入以上数据(包括姓名,三门课的成绩)
输入的格式如:zhangsan,30,40,50    计算出总成绩
并把学会的信息和计算出的总分数高低顺序存放在磁盘文件"student.txt"

【代码】:

import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
	private String name;
	private double chinese;
	private double math;
	private double english;
	private double sum;

	public double getSum(){
		return this.sum;
	}
	Student(String name,double chinese,double math,double english){
		this.name=name;
		this.chinese=chinese;
		this.math=math;
		this.english=english;
		sum=chinese+math+english;
	}

	//重写hashCode()方法
	public int hashCode(){
		return name.hashCode();
	}

	//重写equals()方法
	public boolean equals(Object o){
		if(!(o instanceof Student)){
			throw new RuntimeException("不是学生类对象");
		}
		Student s=(Student)o;
		return this.name.equals(s.name)&&this.sum==s.sum;
	}
	public int compareTo(Student s){
		int num=new Double(this.sum).compareTo(new Double(s.sum));
		if(num==0){
			return this.name.compareTo(s.name);
		}
		return num;
	}
	public String toString(){
		return name+","+chinese+","+math+","+english;
	}
}
class StudentInforTool
{
	public static Set<Student> getStudents()throws IOException{
		return getStudents(null);
	}
	public static Set<Student> getStudents(Comparator<Student> comp) throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String line=null;
		Set<Student> stus=new TreeSet<Student>();
		if(comp==null){
			stus=new TreeSet<Student>();
		}else{
			stus=new TreeSet<Student>(comp);
		}
		while((line=br.readLine())!=null){
			if("over".equals(line))  
				break;
			String[] info=line.split(",");
			Student stu=new Student(info[0],Double.parseDouble(info[1]),
				Double.parseDouble(info[2]),Double.parseDouble(info[3]));
			stus.add(stu);

		}
		return stus;
	}
	public static void writeStudents(Set<Student> stus)throws IOException{
		BufferedWriter bw=new BufferedWriter(new FileWriter("student.txt"));
		
		for(Student stu:stus){
			bw.write(stu.toString()+"\t\t");
			bw.write(stu.getSum()+"");
			bw.newLine();
			bw.flush();
		}
		bw.close();
	}
}
class StuScore
{
	public static void main(String[] args) throws IOException
	{
		Comparator<Student> comp=Collections.reverseOrder();
		Set<Student> stus=StudentInforTool.getStudents(comp);
		StudentInforTool.writeStudents(stus);
	}
}

【输出截图】:

键盘录入:

文件输出:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值