Browse Source

上传至w7文件夹

main
Fuyuxinge 2 months ago
parent
commit
6c0c372789
  1. 19
      w7/ScoreAvg.java
  2. 36
      w7/ScoreAvg2.java

19
w7/ScoreAvg.java

@ -0,0 +1,19 @@
package w7;
import java.io.BufferedReader;
import java.io.FileReader;
public class ScoreAvg {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("scores.txt"));
String line;
int sum = 0;
int count = 0;
while ((line = br.readLine()) != null) {
sum += Integer.parseInt(line);
count++;
}
br.close();
System.out.println((double) sum / count);
}
}

36
w7/ScoreAvg2.java

@ -0,0 +1,36 @@
package w7;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ScoreAvg2 {
public static void main(String[] args) {
String path = "scores.txt";
int sum = 0;
int count = 0;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
while ((line = br.readLine()) != null) {
try {
sum += Integer.parseInt(line);
count++;
} catch (NumberFormatException e) {
System.err.println("跳过无效数字行:" + line);
}
}
if (count > 0) {
System.out.printf("平均分:%.2f%n", (double) sum / count);
} else {
System.out.println("未读取到有效成绩");
}
} catch (IOException e) {
System.err.println("读取文件失败:" + e.getMessage());
e.printStackTrace();
}
}
}
Loading…
Cancel
Save