标签:parent amr href z-index iter text name 通过 12px
练习:
有五个学生,每个学生有3门课程:数学,语文,英语
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:zhangsan, 30, 40, 40计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件”stud.txt”中.
1.描述学生对象;
2.定义一个可操作学生对象的工具类;
思路:
1.通过获取键盘录入的一行数据,并将录入的信息封装成学生对象;
2.因为学生对象很多,且要对学生的总分排序,所以用TreeSet集合;
3.将集合中的信息写入到文件中;
1.import java.io.*;
2.import java.util.*;
3.class StudentInfoTest
4.{
5. public static void main(String[] args) throws IOException
6. {
7. Comparator<Student> comp = Collections.reverseOrder();//因为之前的排序是从小到大排,现在从大到小排,所以定义比较器
8. Set<Student> stus = StudentInfoTool.getStudent(comp);
9. StudentInfoTool.writeToFile(stus);
10. }
11.}
12.class Student implements Comparable<Student>
13.{
14. private String name;
15. private int ma,cn,en;
16. private int sum;
17.
18. Student(String name,int ma,int cn,int en)
19. {
20. this.name = name;
21. this.ma = ma;
22. this.cn = cn;
23. this.en = en;
24. sum = ma + cn + en;
25. }
26. public String getName()
27. {
28. return name;
29. }
30. public int getSum()
31. {
32. return sum;
33. }
34. public String toString()
35. {
36. return "student["+name+", "+ma+", "+cn+", "+en+",]";
37. }
38. public int compareTo(Student stu)
39. {
40. int num = new Integer(this.sum).compareTo(new Integer(stu.sum));
41. if (num==0)
42. {
43. return this.name.compareTo(stu.name);
44. }
45. return num;
46. }
47. public int hashCode()
48. {
49. return name.hashCode()+sum*39;
50. }
51. public boolean equals(Object obj)
52. {
53. if (!(obj instanceof Student))
54. {
55. throw new ClassCastException("传入类型不正确");
56. }
57. Student stu = (Student)obj;
58. return this.name.equals(stu.name) && this.sum==stu.sum;
59. }
60.}
61.class StudentInfoTool
62.{
63. public static Set<Student> getStudent() throws IOException
64. {
65. getStudent(null);
66. return null;
67. }
68. public static Set<Student> getStudent(Comparator<Student> comp) throws IOException
69. {
70. BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
71. String line = null;
72. Set<Student> stus = null;
73. if (comp==null)
74. {
75. stus = new TreeSet<Student>();
76. }
77. else
78. {
79. stus = new TreeSet<Student>(comp);
80. }
81. while ((line=bufr.readLine()) !=null)
82. {
83. if ("over".equals(line))
84. {
85. break;
86. }
87. String[] arr = line.split(",");
88. Student stu = new Student(arr[0],Integer.parseInt(arr[1]),
89. Integer.parseInt(arr[2]),
90. Integer.parseInt(arr[3]));
91. stus.add(stu);
92. }
93. bufr.close();
94. return stus;
95. }
96. public static void writeToFile(Set<Student> stus) throws IOException
97. {
98. BufferedWriter bufw = new BufferedWriter(new FileWriter("e:\\stu.txt"));
99. for (Student stu : stus)
100. {
101. bufw.write(stu.toString());
102. bufw.write(stu.getSum()+"");
103. bufw.newLine();
104. bufw.flush();
105. }
106. bufw.close();
107. }
108.
109.}
110.
111.
标签:parent amr href z-index iter text name 通过 12px
原文地址:http://www.cnblogs.com/RuntimExcep/p/7121155.html