You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

28 lines
1.1 KiB

package W7;
import java.io.BufferedReader; // 导入带缓冲的文本读取类
import java.io.FileReader; // 导入文件读取类
import java.io.IOException; // 导入IO异常类(处理文件读取错误)
public class Scores {
public static void main(String[] args) {
int sum = 0;
try (BufferedReader reader = new BufferedReader(new FileReader("score.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
try {
// 正常步骤:把读到的字符串转成数字
int score = Integer.parseInt(line.trim());
// 正常步骤:分数加起来
sum += score;
} catch (NumberFormatException e) {
// 错误步骤:把异常信息打印出来
System.out.println("数字格式错误: " + line);
}
}
} catch (IOException e) {
System.out.println("文件读取错误: " + e.getMessage());
}
System.out.println("总分是:" + sum);
}
}