本帖最后由 赵海洋 于 2013-7-6 15:29 编辑
package com.oxf.properties;
import java.util.Set;
public class StudentTest {
/*有5个同学,每个同学有3门课的成绩从键盘上输入以上数据(包过姓名,三门成绩)
* 输入的格式:如:zhangsan 30,40,50计算出总成绩,并把学生的信息和计算出的总
* 分数高低顺序存放在磁盘文件“stud.txt”中
*
* 1.描述学生对象
* 2.定义一个可操作的学生对象的工具类
* 思想:
* 1,通过获取键盘录入一行数据,并将该行信息取出封装成学生对象
* 2.因为学生有很多那么久需要存储。使用到集合,因为要对学生的总分排序所以可以使用TreeSet
* 3.将集合的信息希尔到一个文件中
*
* */
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Set<Student>stus=StudentInfoTool.getStudents();
StudentInfoTool.write2File(stus);
}
}
package com.oxf.properties;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;
public class Student implements Comparable<Student>{
private String name;
private int ma,cn,en;
private int sum;
public Student(String name, int ma, int cn, int en) {
this.name = name;
this.ma = ma;
this.cn = cn;
this.en = en;
sum=ma+cn+en;
}
public String getName() {
return name;
}
public int getSum() {
return sum;
}
public int hashCode(){
return name.hashCode()+sum*78;
}
public boolean equals(Object obj){
if(!(obj instanceof Student)){
throw new ClassCastException("类型不匹配");
}
Student s=(Student)obj;
return this.name.equals(s.name)&&this.sum==s.sum;
}
public String toString(){
return "Strudent["+name+","+ma+","+cn+","+en+"]";
}
@Override
public int compareTo(Student o) {
int num =new Integer(this.sum).compareTo(new Integer(o.sum));
if(num==0)
return this.name.compareTo(o.name);
else
return num;
}
}
class StudentInfoTool{
public static Set<Student> getStudents() throws Exception{
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
Set<Student> stus=new TreeSet<Student>();
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.getInteger(info[3]));
stus.add(stu);
}
bufr.close();
return stus;
}
public static void write2File(Set<Student> stus) throws IOException{
BufferedWriter bufw=new BufferedWriter(new FileWriter("d:\\info.txt"));
for(Student s:stus){
bufw.write(s.toString()+"\t");
bufw.write(s.getSum()+" ");
bufw.newLine();
bufw.flush();
}
}
}
控制台:
w,33,33,33
Exception in thread "main" java.lang.NullPointerException
at com.oxf.properties.StudentInfoTool.getStudents(Student.java:65)
at com.oxf.properties.StudentTest.main(StudentTest.java:22)
是什么原因?
|