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

被折叠的 条评论
为什么被折叠?



