黑马程序员技术交流社区

标题: 求大神给个正确答案........万分感谢......... [打印本页]

作者: 我认识你    时间: 2017-2-7 21:27
标题: 求大神给个正确答案........万分感谢.........
1:项目根路径下有文件student.txt,文件中内容是学生的姓名和各科的成绩
张三:81.5,86.0,93.5
李四:78.0,84.0,90.0
王五:59.0,75.5,81.5
(Student.txt文件和内容可手动创建);
2:读取文件内容,计算出总分和平均分;在项目根目录下创建一个“成绩明细.txt”,将计算出的内容(以平均分从小到大)写入“成绩明细.txt”文件中,格式是:
王五:59.0,75.5,81.5 总分:216.0 平均分:72.0
李四:78.0,84.0,90.0 总分:252.0 平均分:84.0
张三:81.5,86.0,93.5 总分:261.0 平均分:87.0
作者: Jet'aime    时间: 2017-2-8 10:22
package com.heima.day1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

/**
*
* @author Administrator
*
*/
public class SumScore {

        /**
         * @param args
         * @throws IOException
         */
        public static void main(String[] args) throws IOException {
                //创建输入流对象,读取Student.txt内容
                BufferedReader br = new BufferedReader(new FileReader("Student.txt"));
                //将读到的内容按行存储到list中
                ArrayList<String> list = new ArrayList<>();
                String line;
                while ((line = br.readLine()) != null) {
                        list.add(line);
                }
                br.close();
                //创建TreeMap对象,便于按平均分排序,键为平均分,值为要打印的学生所有信息字符串
                TreeMap<Double, String> map = new TreeMap<>();
                //遍历list,求出学生平均分并存入map集合
                for (String s : list) {
                        //将学生姓名和成绩分割,取出成绩字符串
                        String[] sName = s.split(":");
                        //取出每科成绩
                        String[] score = sName[1].split(",");
                        double sum = 0;
                        //遍历所有成绩,求出该学生总成绩
                        for (String str : score) {
                                sum += Double.valueOf(str);
                        }
                        //存入学生信息和学生成绩
                        String key = String.format(s + "总分: %f 平均分: %f ", sum, sum / 3);
                        map.put(sum / 3, key);
                }
                //将map集合的内容写入文件
                BufferedWriter bw = new BufferedWriter(new FileWriter("成绩明细.txt"));
                for(Double d : map.keySet()){
                        bw.write(map.get(d));
                        bw.newLine();
                }
                bw.close();
        }

}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2