/*
* 练习:
* 有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括姓名,三门课成绩)
* 输入格式:如 zhangsan,30,40,60 计算出总成绩,并把学生的信息和计算出的总分数
* 高低顺序存放在磁盘文件"stud.txt"中
*
*
*/
import java.io.*;
import java.util.*;
public class StudentInfoTestDemo {
public static void main(String[] args) throws IOException
{
// TODO 自动生成的方法存根
Comparator<Student> cmp=Collections.reverseOrder();
Set<Student> s=StudentInforTool.getStudent(cmp);
StudentInforTool.write(s);
}
}
//描述学生对象
class Student implements Comparable<Student>
{
private String name;
private int man,cn,en;
private int sum;
Student(String name,int man,int cn,int en)
{
this.name=name;
this.man=man;
this.cn=cn;
this.en=en;
sum=man+cn+en;
}
public String getname()
{
return this.name;
}
public int getsum()
{
return this.man+this.en+this.cn;
}
public int hashCode()
{
return this.name.hashCode()+sum*37;
}
public boolean equals(Object obj)throws RuntimeException
{
if(!(obj instanceof Student))
throw new ClassCastException("错误! 不符合要求");
Student stu=(Student)obj;
return this.name.equals(stu)&&this.sum==stu.sum;
}
//覆盖comparaTo方法
public int compareTo(Student stu)
{
int num=new Integer(this.getsum()).compareTo(new Integer(stu.getsum()));
if(num==0)
return this.getname().compareTo(stu.getname());
return num;
}
public String toString()
{
return "name"+name+","+"man"+man+","+"cn"+cn+","+"en"+en;
}
}
//操作学生工具类
class StudentInforTool
{
//没有有比较器的比较(自然顺序)
public static Set<Student> getStudent()throws IOException
{
return getStudent(null);
}
//有比较器的比较(强行逆转自然顺序)
public static Set<Student> getStudent(Comparator<Student> cmp)throws IOException
{
//键盘录入
BufferedReader br=
new BufferedReader(new InputStreamReader(System.in));
Set<Student> stus=null;
if(cmp==null)
new TreeSet<Student>();
else
new TreeSet<Student>(cmp);
String line=null;
while((line=br.readLine())!=null)
{
if("over".equals(line))
break;
String[] str=line.split(",");
Student stu=new Student(str[0],
Integer.parseInt(str[1]),Integer.parseInt(str[2]),Integer.parseInt(str[3]));
stus.add(stu); //报错空指针访问:变量 stus 在此位置只可为空值
}
br.close();
return stus;
}
public static void write(Set<Student> s)throws IOException
{
BufferedWriter bw=new BufferedWriter(new FileWriter("e:\\student.txt"));
for(Student stu:s)
{
bw.write(stu.toString()+"\t");
bw.write(stu.getsum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
------解决思路----------------------
Set<Student> stus=null;你后面又没给stus赋值,对一个null对象操作肯定报空指针异常啊
Set<Student> stus = null;
if (cmp == null)
stus = new TreeSet<Student>();
else
stus = new TreeSet<Student>(cmp);
------解决思路----------------------
+1.
下次可以像楼上这样,把代码贴在代码框里面,会有颜色和行号,。