A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© losttemp 中级黑马   /  2016-5-20 22:39  /  514 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

*键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),
* 按照总分从高到低输出到控制台 .然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。
*         要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。
* 。
* 1.创建键盘录入对象,输入学生成绩
* 2.创建treeset集合传入比较器,以总分作比较
* 3.以学生的个数为判断条件,如果size小于5就进行存储
* 4.将录入的字符串用逗号切割,返回一个字符串数组,将字符串数组从第二个元素转换成int数
* 5.将转换后的结果封装成Student对象,将Student添加到treeset集合中
* 6.遍历集合
* 增加 7.创建bufferwrite输出流 关联"stu",将学生信息转为字符串存到文件中去,每次读取一行.
* 8.关流.
*
*/
public class Test07 {
        public static void main(String[] args) throws Exception {
                Scanner sc = new Scanner(System.in);// 1.创建键盘录入对象,输入学生成绩
                System.out.println("请输入学生成绩按姓名,语文成绩,数学成绩,英语成绩");
                TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
                        // 2.创建treeset集合传入比较器,以总分作比较
                        @Override
                        public int compare(Student S1, Student S2) {

                                int num = S2.getSum() - S1.getSum();
                                return num == 0 ? 1 : num;
                        }
                });

                while (ts.size() < 5) {
                        String str = sc.nextLine();
                        String arr[] = str.split(",");// 将录入的字符串用逗号切割,返回一个字符串数组,将字符串数组从第二个元素转换成int数
                        int chinese = Integer.parseInt(arr[1]);
                        int math = Integer.parseInt(arr[2]);
                        int english = Integer.parseInt(arr[3]);

                        ts.add(new Student(arr[0], chinese, math, english));
                }

                // System.out.println("排序后的学生信息是");
                BufferedWriter bw = new BufferedWriter(new FileWriter("stu.txt"));
                for (Student s : ts) {
                        System.out.println(s);
                        bw.write(s.toString());
                        bw.newLine();
                }
                bw.close();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马