exception处理,catch循环停止
我有一个我需要读取的文件,打印出整数,捕获exception并继续显示下一个整数,依此类推,直到没有更多的整数。
该文件包含:12 5 sd 67 4 cy
我希望它显示:
12
五
输入错误
67
4
输入错误
但是,它只给我12,5,然后输入错误,它停止。 我已经尝试将所有内容放入while循环中,并且无限循环地输入exception。
public static void readNumbers() { File inputFile = new File ("C:/users/AC/Desktop/input.txt"); try { Scanner reader = new Scanner(inputFile); while(reader.hasNext()) { 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!"); } } }
我错过了什么,以便循环继续读取下一个int,依此类推?
try / catch块需要在循环内部。
抛出exception时,控制会尽可能地突破,直到遇到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循环中,并且无限循环地输入exception。
你提到你已经尝试过了。 我需要有关您遇到的问题的更多详细信息,因为这是正确的方法。 在我的脑海中,只是预感,或许reader.nextInt()在exception发生时不会提升读者在文件中的位置,因此再次调用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]
我推进读者是正确的。
根据Scanner的Java文档:
将输入的下一个标记扫描为int。 如果下一个标记无法转换为有效的int值,则此方法将抛出InputMismatchException,如下所述。 如果翻译成功,扫描仪将超过匹配的输入。
把try 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!"); } }
编辑:请注意,此代码导致循环无限循环导致InputMismatchException的第一行。 请注意修复此错误的已接受答案。
当exception发生时,控制到达匹配的catch块,然后到达catch块之后的后续行。 在你的情况下匹配catch在while循环之外,因此while循环停止。 在while循环中移动相应的catch块。 在你的代码reader.nextInt();
是可能导致InputMismatchException
的潜在行。
try { int num = reader.nextInt(); System.out.println("Number read: " +num); } catch (InputMismatchException e) { System.out.println("Input error "); }