try / catch块需要在循环内部。
当引发异常时,控制会尽可能地爆发,直到遇到遇到catch块的情况为止(在您的情况下,该catch块在循环之外)。
public static void readNumbers(){ File inputFile = new File ("C:/users/AC/Desktop/input.txt"); try { Scanner reader = new Scanner(inputFile); while(reader.hasNext()) { try { int num = reader.nextInt(); System.out.println("Number read: " +num); } catch (InputMismatchException e) { System.out.println("Input error "); } } } catch (FileNotFoundException e2) { System.out.println("File not found!"); }}我尝试将所有内容放入while循环中,并且由于输入异常而无休止地循环。
您提到您已经尝试过了。我需要您遇到的问题的更多详细信息,因为这是正确的方法。我的头顶上只是一个预感,也许是当发生异常时reader.nextInt()不会提高读者在文件中的位置,因此再次调用nextInt会读取相同的非整数块。
也许您的catch块需要调用reader.getSomethingElse?像reader.next()一样?
这是一个主意,我还没有测试过:
public static void readNumbers(){ File inputFile = new File ("C:/users/AC/Desktop/input.txt"); try { Scanner reader = new Scanner(inputFile); while(reader.hasNext()) { try { int num = reader.nextInt(); System.out.println("Number read: " +num); } catch (InputMismatchException e) { System.out.println("Input error "); reader.next(); // THIS LINE IS NEW } } } catch (FileNotFoundException e2) { System.out.println("File not found!"); }}[编辑9:32 PM]
我对提升读者是正确的。
根据扫描仪的Java文档:
将输入的下一个标记扫描为int。如果下一个标记不能转换为有效的int值,则此方法将引发InputMismatchException,如下所述。
如果翻译成功,则扫描程序将前进经过匹配的输入。
http://docs.oracle.com/javase/7/docs/api/



