2 changed files with 55 additions and 0 deletions
@ -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); |
|||
} |
|||
} |
|||
@ -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…
Reference in new issue