黑马程序员 IO和集合的小练习

本文介绍了一个使用Java实现的学生信息管理系统,该系统能够录入学生的姓名及三门课程的成绩,并计算总成绩,最后按成绩高低顺序将数据写入文件。系统利用了TreeSet进行排序,实现了从键盘读取数据并写入到硬盘的功能。

  ----------- android培训java培训、java学习型技术博客、期待与您交流! ------------

需求:五个学生,每个学生有三门成绩,从键盘录入以上数据包括(姓名,三门课的成绩)

如:zhangsan ,30,40,50    计算总成绩,并把信息和计算的结果的高低顺序写入硬盘的“stu.ext”。

分析:1,建立学生对象。

    2,建立一个类,可以操作学生。里面要建立集合。

import java.io.*;
import java.util.*;
class  StudentTest
{
	public static void main(String[] args) 
	{
		StudentTool.get();
	}
}
class StudentTool
{
	public static void  get()
	{
		BufferedReader bfr = null;
		BufferedWriter bfw = null;
		TreeSet<Student> ts = new TreeSet<Student>();
		try
		{
			bfr = new BufferedReader(new InputStreamReader(System.in));
			bfw = new BufferedWriter(new FileWriter("stud.txt"));
			String st = null;
			while ((st = bfr.readLine()) != null)
			{
				if("over".equals(st))
					break;
				String[] sz = st.split(",");
				Student stu = new Student(sz[0],Integer.parseInt(sz[1]),
												Integer.parseInt(sz[2]),
												Integer.parseInt(sz[3]));
				ts.add(stu);
			}
			for(Student info : ts)
			{
				bfw.write(info.toString()+  "-----");
				bfw.write(info.getSum()+ "");
				bfw.newLine();
				bfw.flush();
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("cuo");
		}
		finally
		{
			try
			{
				if(bfr != null)
					bfr.close();
			}
			catch (IOException e )
			{
				throw new RuntimeException("cuol");
			}
			try
			{
				if(bfw != null)
					bfw.close();
			}
			catch (IOException e )
			{
				throw new RuntimeException("cuo2");
			}
		}
	}
}
class Student implements Comparable<Student>
{
	private String name;
	private int ms,yw,eg;
	private int sum;
	Student(String name, int ms, int yw, int eg)
	{
		this.name = name;
		this.ms = ms;
		this.yw = yw;
		this.eg = eg;
		sum = ms + yw + eg;
	}
	public String getName()
	{
		return name;
	}
	public int getSum()
	{
		return sum;
	}

	public int compareTo( Student s)
	{
		int num = (new Integer(s.sum)).compareTo(new Integer(this.sum));
		if(num == 0)
			num = s.name.compareTo(this.name);
		return num;
	}
	public int hashCode()
	{
		return name.hashCode() + sum * 7;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new RuntimeException("类型不匹配");
		Student st = (Student)obj;
		return this.name.equals(st.name) && this.sum ==st.sum;
	}
	public String toString()
	{
		return  "["+name + "]" + "[" + ms +"]" +"["+ yw + "]" + "["+ eg + "]";
	}
}

    -----------  android培训 java培训 、java学习型技术博客、期待与您交流! ------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值