- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Set;
- import java.util.TreeSet;
- /*
- * 把学生成绩存储在stu.txt文件中,并按照总分由高到低的顺序排序
- */
- public class StudentInfoTest {
- public static void main(String[] args) {
- Comparator<Student> comp=Collections.reverseOrder();
- Set<Student> set=StuInfoTool.getInfo(comp);
- StuInfoTool.WriteInfoToTest(set);
- }
- }
- //定义工具类
- class StuInfoTool{
-
- //通过键盘获取学生成绩
- public static Set<Student> getInfo(){
- return getInfo(null);
- }
- public static Set<Student> getInfo(Comparator<Student> comp){
- BufferedReader br=null;
- Set<Student> set=null;
- if(comp==null){
- set=new TreeSet<Student>();
- }else{
- set=new TreeSet<Student>(comp);
- }
- try{
- br=new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- while((line=br.readLine())!=null){
- if(line.equals("over")){
- break;
- }
- String[] info=line.split(",");
- Student stu=new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));
- set.add(stu);
- }
- }catch(IOException e){
- throw new RuntimeException("输入失败");
- }finally{
- try {
- if (br != null) {
- br.close();
- }
- } catch (IOException e2) {
- throw new RuntimeException("输入流关闭失败");
- }
- }
- return set;
- }
-
- //将获取的信息保存到文本文件中
- public static void WriteInfoToTest(Set<Student> set){
- BufferedWriter bw=null;
- try{
- bw=new BufferedWriter(new FileWriter("stuinfo.txt"));
- for(Student stu:set){
- bw.write(stu.toString());
- bw.newLine();
- bw.flush();
- }
- }catch(IOException e){
- throw new RuntimeException("写入文本文件失败");
- }finally{
- try {
- if (bw != null) {
- bw.close();
- }
- } catch (IOException e2) {
- throw new RuntimeException("写入流关闭失败");
- }
- }
- }
- }
- //学生类
- class Student implements Comparable<Student>{
- private String name;
- private int ch,ma,en,sum;
-
- public Student(String name, int ch, int ma, int en) {
- this.name = name;
- this.ch = ch;
- this.ma = ma;
- this.en = en;
- sum=ch+ma+en;
- }
-
- @Override
- public int hashCode() {
- return name.hashCode()+sum;
- }
-
- @Override
- public boolean equals(Object obj) {
- if(!(obj instanceof Student)){
- throw new RuntimeException("类型不匹配");
- }
- Student stu=(Student)obj;
- return this.name.equals(stu.name) && this.ch==stu.ch && this.ma==stu.ma && this.en==stu.en;
- }
- @Override
- public int compareTo(Student stu) {
- int num=new Integer(this.sum).compareTo(new Integer(stu.sum));
- if(num==0){
- return this.name.compareTo(stu.name);
- }
- return sum;
- }
-
- @Override
- public String toString() {
- return name+":"+ch+" "+ma+" "+en+"\t"+sum;
- }
- }
复制代码
|