2 changed files with 46 additions and 0 deletions
@ -0,0 +1,35 @@ |
|||
package W7; |
|||
|
|||
public class ScoreAverage { |
|||
public 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){ |
|||
line=line.trim(); |
|||
if (line.isEmpty()){ |
|||
continue; |
|||
} |
|||
try{ |
|||
int score=Integer.parseInt(line); |
|||
sum += score; |
|||
count++; |
|||
}catch (NumberFormatException e){ |
|||
System.err.println("无效的数字:" + line); |
|||
} |
|||
} |
|||
if (count==0){ |
|||
System.out.println("文件中没有有效成绩"); |
|||
}else{ |
|||
double average = (double) sum / count; |
|||
System.out.println("平均成绩为:" + average); |
|||
} |
|||
}catch (FileNotFoundException e){ |
|||
System.err.println("文件不存在:" + filePath); |
|||
}catch (IOException e){ |
|||
System.err.println("读取文件时出错:" + e.getMessage()); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
package W7; |
|||
|
|||
public class ScoreCalculator { |
|||
BufferedReader br=new BufferedReader(new FileReader("scores.txt")); |
|||
String line; |
|||
while ((line=br.readLine())!=null){ |
|||
sum +=Integer.parseInt(line); |
|||
} |
|||
br.close(); |
|||
} |
|||
|
|||
Loading…
Reference in new issue