4 changed files with 52 additions and 0 deletions
@ -0,0 +1,33 @@ |
|||||
|
package w7; |
||||
|
|
||||
|
import java.io.BufferedReader; |
||||
|
import java.io.FileNotFoundException; |
||||
|
import java.io.FileReader; |
||||
|
import java.io.IOException; |
||||
|
|
||||
|
public class AverageScoreAfter { |
||||
|
public static void main(String[] args) { |
||||
|
int sum = 0, 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 { |
||||
|
sum += Integer.parseInt(line); |
||||
|
count++; |
||||
|
} catch (NumberFormatException e) { |
||||
|
System.err.println("忽略无效数字:" + line); |
||||
|
} |
||||
|
} |
||||
|
} catch (FileNotFoundException e) { |
||||
|
System.err.println("文件不存在"); |
||||
|
return; |
||||
|
} catch (IOException e) { |
||||
|
System.err.println("读取错误"); |
||||
|
return; |
||||
|
} |
||||
|
if (count == 0) System.err.println("无有效成绩"); |
||||
|
else System.out.printf("平均分:%.2f%n", (double) sum / count); |
||||
|
} |
||||
|
} |
||||
Binary file not shown.
@ -0,0 +1,19 @@ |
|||||
|
package w7; |
||||
|
|
||||
|
import java.io.BufferedReader; |
||||
|
import java.io.FileReader; |
||||
|
import java.io.IOException; |
||||
|
|
||||
|
public class AverageScoreBefore { |
||||
|
public static void main(String[] args) throws IOException { |
||||
|
BufferedReader br = new BufferedReader(new FileReader("scores.txt")); |
||||
|
String line; |
||||
|
int sum = 0, count = 0; |
||||
|
while ((line = br.readLine()) != null) { |
||||
|
sum += Integer.parseInt(line); |
||||
|
count++; |
||||
|
} |
||||
|
br.close(); |
||||
|
System.out.println("平均分:" + (double) sum / count); |
||||
|
} |
||||
|
} |
||||
|
After Width: | Height: | Size: 228 KiB |
Loading…
Reference in new issue