我有一个id没有名字和成绩的文本文件我想提取ID no,然后成绩然后计算平均值并将其附加到另一个文件

时间:2016-12-09 12:16:22

标签: file append extract

PrintWriter out = new PrintWriter(new FileWriter(" students.txt",true));     做       {          //从用户那里获取信息以写入文件          System.out.print("输入学生ID:");          idNo = keyIn.nextLine();          System.out.print("输入学生姓名:");          name = keyIn.nextLine();          System.out.print("输入学生成绩:");          grades = keyIn.nextInt();          keyIn.nextLine(); //清除缓冲区

     out.println(idNo +" " +name +" " +grades);        //write line to output file

     System.out.print("Do You Have Another Student To Process: ");
     response = keyIn.next().charAt(0);
     keyIn.nextLine(); //clear buffer


  }while(response != 'n');     
    //close files
  out.close();
    //in.close();

中断;

案例2://将学生测试标记写入results.txt

1 个答案:

答案 0 :(得分:0)

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer >();
    while ((line = br.readLine()) != null) {
       String temp[]=line.split(" ");
       if (map.containsKey(Integer.parseInt(temp[0]))) {
           int val=hmap.get[Integer.parseInt(temp[0])];
           val+=Integer.parseInt(temp[2]);
           map.put(Integer.parseInt(temp[0]),val);
       } else {
          map.put(Integer.parseInt(temp[0]),Integer.parseInt(temp[2]));
       }
    }
}
try{
    PrintWriter writer = new PrintWriter("results.txt", "UTF-8");
    Iterator it = hmap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        writer.println(pair.getKey() + " " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
    writer.close();
} catch (IOException e) {
   // do something
}