把集合中的student對象信息儲存在文本中
阿新 • • 發佈:2018-06-14
@override out compare stat buffere 遍歷集合 AD IT auth
1.student類
1 // 姓名 2 private String name; 3 // 語文成績 4 private int chinese; 5 // 數學成績 6 private int math; 7 // 英語成績 8 private int english;
public int getSum() { return this.chinese + this.math + this.english; }
2.studentTest類
1 /** 2 * * 鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績),按照總分從高到低存入文本文件 3 * 4 * 分析: 5 * A:創建學生類 6 * B:創建集合對象 7 * TreeSet<Student> 8 * C:鍵盤錄入學生信息存儲到集合 9 * D:遍歷集合,把數據寫到文本文件 10 * @author chenwen 11 * 12 */ 13 public class StudentTest7 { 14 15 publicstatic void main(String[] args) throws IOException { 16 TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() { 17 18 @Override 19 public int compare(Student s1, Student s2) { 20 int num=s1.getSum()-s2.getSum(); 21 intnum2=num==0?s1.getChinese()-s2.getChinese():num; 22 int num3=num2==0?s1.getMath()-s2.getMath():num2; 23 int num4=num3==0?s1.getName().compareTo(s2.getName()):num3; 24 return num4; 25 } 26 }); 27 // 鍵盤錄入學生信息存儲到集合 28 for(int x =1;x<=5;x++) { 29 Scanner sc = new Scanner(System.in); 30 System.out.println("請輸入第"+x+"個學生的信息"); 31 System.out.println("姓名"); 32 String name =sc.nextLine(); 33 System.out.println("語文成績"); 34 int chinese =sc.nextInt(); 35 System.out.println("數學成績"); 36 int math =sc.nextInt(); 37 System.out.println("英語成績"); 38 int english =sc.nextInt(); 39 40 Student s= new Student(); 41 s.setName(name); 42 s.setChinese(chinese); 43 s.setMath(math); 44 s.setEnglish(english); 45 ts.add(s); 46 } 47 // 遍歷集合,把數據寫到文本文件 48 BufferedWriter bw =new BufferedWriter(new FileWriter("student.txt")); 49 bw.write("學生信息如下:"); 50 bw.newLine(); 51 bw.flush(); 52 bw.write("姓名,語文成績,數學成績,英語成績"); 53 bw.newLine(); 54 bw.flush(); 55 for (Student s : ts) { 56 StringBuilder sb =new StringBuilder(); 57 sb.append(s.getName()).append(","). 58 append(s.getChinese()).append(","). 59 append(s.getMath()).append(","). 60 append(s.getEnglish()); 61 bw.write(sb.toString()); 62 bw.newLine(); 63 bw.flush(); 64 } 65 bw.close(); 66 System.out.println("學生信息儲存完畢!"); 67 }
把集合中的student對象信息儲存在文本中