import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;
/*有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。
1,描述学生对象。
2,定义一个可操作学生对象的工具类。
思想:
1,通过获取键盘录入一行数据,并将该行中的信息取出封装成学生对象。
2,因为学生有很多,那么就需要存储,使用到集合。因为要对学生的总分排序。
所以可以使用TreeSet。
3,将集合的信息写入到一个文件中。*/
class Student implements Comparable<Student>
{
private String name;
private int math, chinese, english, sum;
Student(String name, int math, int chinese, int english)
{
this.name = name;
this.math = math;
this.chinese = chinese;
this.english = english;
sum = this.math + this.chinese + this.english;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
public int compareTo(Student s)
{
int num = (((Integer)this.sum).compareTo((Integer)s.sum));
if(num == 0)
return this.name.compareTo(s.name);
return num;
}
}
class StudentInfoTool
{
public static Set<Student> addStudents()
{
BufferedReader br = null;
TreeSet<Student> ts = new TreeSet<Student>();
try
{
br = new BufferedReader(new InputStreamReader(System.in));
String info = "";
while ((info = br.readLine()) != null)
{
if(info.equals("over"))
break;
String[] student = info.split(",");
ts.add(new Student(student[0], Integer.parseInt(student[1]),
Integer.parseInt(student[2]),
Integer.parseInt(student[3])));
}
} catch (Exception e)
{
e.toString();
}
finally
{
try
{
if(br != null)
br.close();
} catch (Exception e)
{
e.toString();
}
}
return ts;
}
public static void writeStuInfo(Set<Student> stuinfo)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\StudentInfo.txt"));
for (Student student : stuinfo)
{
bw.write(student.getName()+"\t\t");
bw.write(student.getSum()+"");
bw.newLine();
}
} catch (Exception e)
{
e.toString();
}
finally
{
try
{
if(bw != null)
bw.close();
} catch (Exception e2)
{
// TODO: handle exception
}
}
}
}
public class StudentInfoTest
{
/**
* @param args
*/
public static void main(String[] args)
{
Set<Student> ts =StudentInfoTool.addStudents();
StudentInfoTool.writeStuInfo(ts);
}
}
|
|