对于大学作业,我们刚刚被介绍尝试捕获异常处理方法,并且有一些与之相关的作业。 我们的任务是创建一个文件,该文件由添加在一起并显示总数的数字组成。 但是,Anything BUT INTEGER应该在文件中的任何位置被忽略,并且应该继续。例如 五 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