需求:
定义学生类,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。
步奏:
1,描述学生对象。
2,定义一个可操作学生对象的工具类。
思路:
1,键盘录入一行数据,将该行数据封装成学生对象
2,学生对象需要存储,用到集合,对学生进行总分排序,可使用TreeSet
3,将集合中的信息写入到一个文件中
实现过程:
import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int cn,ma,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 int getSum(){ //获取学生总分
return sum;
}
public String toString(){ //获取学生信息
return "student["+name+" 语文:"+cn+" 数学:"+ma+" 英语:"+en+" 总分:"+sum+"]";
}
public int hashCode(){ //复写hashSet集合的hashCode()方法
return name.hashCode()+sum*22;
}
public boolean equals(Object obj){ //复写TreeSet集合的equals方法
if(!(obj instanceof Student)) //健壮性判断
throw new ClassCastException("请输入学生的信息!");
Student s = (Student)obj; //转型
return this.name.equals(s.name) && this.sum==s.sum;
}
public int compareTo(Student s){ //覆盖compareTo方法
int num = new Integer(this.sum).compareTo(new Integer(s.sum));//要将int型包装成对象才能使用CompareTo()方法
if(num==0)
return this.name.compareTo(s.name); //如果总分相同,按照姓名排序
return num;
}
}
class StudentInfoTool //获取信息
{
public static Set<Student> getStudents() throws IOException
{
return getStudents(null); //不带比较器的集合
} //带比较器的集合
public static Set<Student> getStudents(Comparator<Student> comp) throws IOException
{
System.out.println("请按照指定的格式录入成绩:学生姓名,语文,数学,英语");
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Student> stu = null;
if(comp==null)
stu = new TreeSet<Student>(); //不带比较器的集合,使用Student类内部compareTo()
else
stu = new TreeSet<Student>(comp);//带比较器的集合
while ((line=bufr.readLine()) !=null)
{
if("over".equals(line))
break; //输入over时退出程序
String[] info = line.split(",");//将读取的字符在","切割成字符数组
Student s = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));
//String转int
stu.add(s); //往集合中添加元素
}
bufr.close(); //关闭资源
return stu;
}
public static void writeToFile(Set<Student> stu) throws IOException
{
BufferedWriter bufw = new BufferedWriter(new FileWriter("studentsInfo.txt"));//创建文档存储信息
for(Student s:stu) //遍历集合
{
bufw.write(s.toString());//将集合中对象转成字符串写入文档
bufw.newLine(); //换行
bufw.flush(); //刷新流
}
bufw.close();//关闭流
}
}
class StudentInfoTest
{
public static void main(String[] args) throws IOException
{
Comparator<Student> comp = Collections.reverseOrder();//反转比较器
Set<Student> stu = StudentInfoTool.getStudents(comp);//获取Student对象集合
StudentInfoTool.writeToFile(stu); //将集合中数据写入到文档中
}
}