diff --git a/w7/Scorecalculator.java b/w7/Scorecalculator.java new file mode 100644 index 0000000..84151f0 --- /dev/null +++ b/w7/Scorecalculator.java @@ -0,0 +1,29 @@ +import java.io.*; +public class Scorecalculator{ + public static void main(String[] args) { + String filepath="scores.txt"; + int sum=0; + int count=0; + try (BufferedReader br = new BufferedReader(new FileReader(filepath))){ + String line; + while ((line=br.readLine()) != null) { + try { + sum+=Integer.parseInt(line.trim()); + count++; + } catch (NumberFormatException e){ + System.out.println("数字格式错误,跳过该行:"+ line); + } + } + if (count>0){ + double average=(double)sum/count; + System.out.println("平均分"+average); + } else { + System.out.println("没有有效成绩数据"); + } + } catch (FileNotFoundException e) { + System.out.println("错误:文件不存在-"+filepath); + } catch (IOException e) { + System.out.println("错误,读取文件时发生错误-"+e.getMessage()); + } + } +} \ No newline at end of file