5 changed files with 59 additions and 0 deletions
@ -0,0 +1,18 @@ |
|||||
|
package java01; |
||||
|
|
||||
|
// 加上这三行!
|
||||
|
import java.io.BufferedReader; |
||||
|
import java.io.FileReader; |
||||
|
import java.io.IOException; |
||||
|
|
||||
|
public class AverageScoreBefore { |
||||
|
public static void main(String[] args) throws Exception { |
||||
|
int sum = 0; |
||||
|
BufferedReader br = new BufferedReader(new FileReader("scores.txt")); |
||||
|
String line; |
||||
|
while ((line = br.readLine()) != null) { |
||||
|
sum += Integer.parseInt(line); |
||||
|
br.close(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,41 @@ |
|||||
|
package java01; |
||||
|
import java.io.BufferedReader; |
||||
|
import java.io.FileReader; |
||||
|
import java.io.IOException; |
||||
|
public class ScoreAverage { |
||||
|
public static void main(String[] args) { |
||||
|
int sum = 0; |
||||
|
int count = 0; |
||||
|
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) { |
||||
|
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.out.println("无效数据,跳过:" + line); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (count > 0) { |
||||
|
double average = (double) sum / count; |
||||
|
System.out.println("总分:" + sum); |
||||
|
System.out.println("有效人数:" + count); |
||||
|
System.out.printf("平均分:%.2f\n", average); |
||||
|
} else { |
||||
|
System.out.println("无有效成绩"); |
||||
|
} |
||||
|
|
||||
|
} catch (java.io.FileNotFoundException e) { |
||||
|
System.out.println("错误:未找到 scores.txt 文件"); |
||||
|
} catch (IOException e) { |
||||
|
System.out.println("读取文件时发生IO异常"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 143 KiB |
|
After Width: | Height: | Size: 151 KiB |
Loading…
Reference in new issue