我正在尝试从文件中读取一堆数字并将它们相加。但我也在文件中添加了一些字符串。我现在正在尝试读取数字将它们加在一起并使用 try/catch 块我试图在文件读取字符串而不是整数时显示错误。但是,一旦代码从文件中读取一个字符串,它就会给我错误,代码不会继续将数字相加。它只是打印错误并打印 0。如何修改它以便它继续读取数字并将它们相加并在读取字符串后显示错误消息。
代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class AddNumbers {
public static void main (String[]args) {
try{
File myFile = new File("numbers.txt");
Scanner scan = new Scanner(myFile);
int x;
int y = 0;
try{
//Read file while it has a line
while(scan.hasNextLine()){
//scan a integer value
x = scan.nextInt();
//Add the scanned value to y
y = y+x;
}
}catch(InputMismatchException e){
//If a string is found then print this error
System.err.println("Strings found! Error!");
}
System.out.println(y);
scan.close();
}catch(FileNotFoundException e){
System.err.println("No such file exists!");
System.out.println();
}
}
}
文件内容
Albert
10000
20000
30000
Ben
50000
12000
Charlie