2、通过实验1,获得如下格式的成绩单score.txt,例如:
姓名:张三,数学72分,物理67分,英语70分.
姓名:李四,数学92分,物理98分,英语88分.
姓名:周五,数学68分,物理80分,英语77分.
要求按行读取成绩单,并在该行的后面加上该同学的总成绩,然后再将该行写入到一个名字为scoreAnalysis.txt的文件中
package com.an;
import java.io.*;
public class AnalysisResult {
public static void main(String args[]) {
File fRead = new File("score.txt");
File fWrite = new File("socreAnalysis.txt");
Writer out = new FileWriter(fWrite, true);//以尾加方式创建指向文件fWrite的out流
BufferedWriter bufferWrite = new BufferedWriter(out);//创建指向out的bufferWrite流
Reader in = new FileReader(fRead);//创建指向文件fRead的in流
BufferedReader bufferRead = new BufferedReader(in);//创建指向in的bufferRead流
String str = null;
while((str=bufferRead.readLine())!=null) {
double totalScore=Fenxi.getTotalScore(str);
str = str+" 总分:"+totalScore;
System.out.println(str);
bufferWrite.write(str);
bufferWrite.newLine();
}
bufferRead.close();
bufferWrite.close();
}
}
package com.an;
import java.util.*;
public class Fenxi {
public static double getAverageScore(String s){ // 自定义方法getTotalScore
Scanner scanner = new Scanner(s);
scanner.useDelimiter("[^0123456789.]+"); // scanner调用useDelimiter(String regex)方法,向参数传递 “[^0123456789.]+”做分隔符
double totalScore=0;
while(scanner.hasNext()){
try{
double score = scanner.nextDouble();
totalScore = totalScore+score;
}
catch(InputMismatchException exp){
String t = scanner.next();
}
}
return totalScore;
}
}