【java编程】IO流和集合类综合题目

需求:

1.有5个学生,每个学生有三门功课

2.从键盘输入以上数据(姓名,三门课成绩)

3.输入格式为:zhangshan,30,40,60并计算出总成绩

4.把学生信息和计算出来的总成绩按从低到高的顺序进行存储

思路:

1.先创建一个学生对象,实现比较器,让学生对象自身具备比较性,同时要复写hashcode()和equeas()方法

2.创建键盘录入,同时创建TreeSet集合,将键盘录入的数据存入集合

3.将集合中的数据存入到文件中

import java.io.*;
import java.util.*;
class  StudentInfoTest
{
	public static void main(String[] args) throws IOException
	{
		//自定义比较器
		Comparator<Student> cmp=Collections.reverseOrder();
		Set<Student> treeset=StudentInfoTool.getStudentInfo(cmp);
		StudentInfoTool.writeToFile(treeset);
	}
}
//创建学生对象
class Student implements Comparable<Student>
{
	private String name;
	private int cn;
	private int ma;
	private int en;
	private int sum;
	Student(String name,int cn,int ma,int en)
	{
		this.name=name;
		this.cn=cn;
		this.ma=ma;
		this.en=en;
		sum=cn+ma+en;
	}
	public String getName()
	{
		return name;
	}
	public int getSum()
	{
		return sum;
	}
	//复写hashCode方法
	public int hashCode()
	{
		return this.name.hashCode()+sum*6;
	}
	//复写equals方法
	public boolean equals(Object obj)
	{
		if(obj instanceof Student)
			throw new ClassCastException("类型不匹配!");
		Student str=(Student)obj;
		return this.name.equals(str.getName()) && this.sum==str.getSum();		
	}
	public int compareTo(Student s)
	{
		int num=new Integer(this.sum).compareTo(new Integer(s.sum));
		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
	public String toString()
	{
		return "["+name+", "+cn+", "+ma+", "+en+"]";
	}
}
//创建操作学生的工具类
class StudentInfoTool
{
	//空比较器
	public static Set<Student> getStudentInfo() throws IOException
	{
		return StudentInfoTool.getStudentInfo(null);		
	}
	public static Set<Student> getStudentInfo(Comparator<Student> cmp) throws IOException
	{
		//键盘录入
		BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
		//创建TreeSet集合,cmp为自定义比较器
		Set<Student> treeset=new TreeSet<Student>(cmp);		
		String line=null;
		while((line=bufr.readLine())!=null)
		{
			if("over".equals(line))
				break;
			//通过","对学生信息进行切割
			String[] info=line.split(",");
			Student stu=new Student(info[0],Integer.parseInt(info[1]),
									Integer.parseInt(info[2]),
									Integer.parseInt(info[3]));
			treeset.add(stu);
		}
		bufr.close();
		System.out.println(treeset);
		return treeset;
	}
	//存入文件方法
	public static void writeToFile(Set<Student> stu) throws IOException
	{
		//文件写入流
		BufferedWriter bufw=new BufferedWriter(new FileWriter("studentInfo.txt"));
		//从集合里取出学生信息
		for(Student s : stu)
		{
			bufw.write(s.toString()+"\t");
			bufw.write(s.getSum()+"");
			bufw.newLine();
			bufw.flush();
		}	
		bufw.close();
	}
}



  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值