Exception handling 使用try&;catch,如何验证文件中的内容

Exception handling 使用try&;catch,如何验证文件中的内容,exception-handling,try-catch,Exception Handling,Try Catch,对于一个大学作业,我们刚刚被介绍尝试捕获异常处理方法,并与之相关联的一些作业工作。 我们的任务是创建一个包含数字的文件,这些数字相加后显示总数。 但是,除了整数以外的任何内容都应该被忽略,并且应该继续。例如 5. 6. G 10 应该加5+6+10并忽略g,但出于某种原因,我无法解决如何忽略除INT以外的任何内容。此外,我需要它,因此如果程序的第一行是g,它将被忽略并继续向下添加所有整数 因此,我很难让程序显示文件的内容 public static void main(String[] args

对于一个大学作业,我们刚刚被介绍尝试捕获异常处理方法,并与之相关联的一些作业工作。 我们的任务是创建一个包含数字的文件,这些数字相加后显示总数。 但是,除了整数以外的任何内容都应该被忽略,并且应该继续。例如 5. 6. G 10 应该加5+6+10并忽略g,但出于某种原因,我无法解决如何忽略除INT以外的任何内容。此外,我需要它,因此如果程序的第一行是g,它将被忽略并继续向下添加所有整数

因此,我很难让程序显示文件的内容

public static void main(String[] args) throws FileNotFoundException {

    int numbers = 0;
    int total = 0;
    Scanner fileScan = null;

    try{
    File integers = new File("integers.txt");
    fileScan = new Scanner(integers);
    // Loops through file and adds up

        while(fileScan.hasNextLine()){
                numbers = fileScan.nextInt();
                System.out.println(numbers);        
                total+=numbers;

        }
        //fileScan.next();
    System.out.print("Normal Total: " +total);
        }
    catch(FileNotFoundException ex){
            System.err.println("Missing file try again!");
    }
    catch(InputMismatchException ex){
        System.err.print("result through input exception\n");

        //System.out.println(total);
        //total+=numbers;
    }
    catch(NoSuchElementException ex){
        System.err.println("Cannot find error");
    }
    finally{

        System.out.println("\nTotal through finally: "+total);
        fileScan.close();
    }

}

}

 AND the file output is:

result through input exception
6
8

Total through finally: 14

如果您试图忽略InputMisMatchException(读取字符串/字符时触发),请尝试注释掉System.err并放置continue;在那里。我是的,我想让它忽略字符串并读取它下面的下一个int,但它说continues不能放在loopOk之外,所以只需注释掉System.err语句,不要麻烦使用continue。。如果这是一个运行时异常,它应该迭代到loopHmm的下一部分,但遗憾的是,它仍然无法工作。它不显示数字和总数..是否取消了System.out.println(总数)和total+=数字的注释?仅供参考,您应该将总数+=放在print语句之前。如果您试图忽略InputMisMatchException(读取字符串/字符时触发),请尝试注释System.err并放置continue;在那里。我是的,我想让它忽略字符串并读取它下面的下一个int,但它说continues不能放在loopOk之外,所以只需注释掉System.err语句,不要麻烦使用continue。。如果这是一个运行时异常,它应该迭代到loopHmm的下一部分,但遗憾的是,它仍然无法工作。它不显示数字和总数..是否取消了System.out.println(总数)和total+=数字的注释?仅供参考,您应该将总数+=放在打印语句之前