我正在尝试创建一个程序,从文件中读取整数列表,并将它们全部添加在一起并显示给用户。我可以让这个程序正常工作,但我想要做的是拥有它,这样如果文件中存在无效条目(例如,单词或任何不是数字的内容),它会提醒用户并忽略无效条目数据并跳至下一个可用号码。这是到目前为止我的代码:
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class IntegerReadIn {
public static void main(String[] args) {
int sum = 0;
try {
File myFile = new File("IntegerReadIn.txt");
Scanner scan = new Scanner(myFile);
while (scan.hasNextInt()) {
sum = sum + scan.nextInt();
}
System.out.println("Total = " + sum);
scan.close();
} catch (FileNotFoundException e) {
System.err.println("No such file name");
} catch (InputMismatchException e) {
System.err.println("Invalid entry found - integers only.");
}
}
}
最佳答案
首先使用nextLine()读取整行。之后使用 Integer.parseInt() 方法来验证整数输入。
Scanner scan = new Scanner(myFile);
String s = scan.nextLine();
try{
Integer.parseInt(s);
}
catch(NumberFormatException ex){
System.out.println("Error....");
}
关于java - Java中忽略文件中的无效数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27408945/