我正在尝试创建一个程序,该程序从文件中读取整数列表,并将它们全部加在一起并显示给用户。我可以使该程序正常运行,但是我想要做的就是拥有它,因此,如果文件中存在无效条目(例如,单词或非数字的任何内容),它将提醒用户并忽略无效的条目数据并跳至下一个可用号码。到目前为止,这是我的代码:

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....");
}

10-07 19:23
查看更多