用户错误后返回扫描仪读取 – java

我已经读取了必须只有int类型的用户输入,当用户输入字母而不是int时会出现问题。 我知道如何处理exception,但我想将扫描器读回到用户犯了错误的位置。 我能怎么做? 我已经尝试过无限循环,但它不起作用。

try{ System.out.print("enter number: "); value = scanner.nextInt(); }catch(InputMismatchException e){ System.err.println("enter a number!"); } 

虽然其他答案为您提供了使用循环的正确想法,但您应避免将exception用作基本逻辑的一部分。 相反,您可以使用Scanner hasNextInt来检查用户是否传递了整数。

 System.out.print("enter number: "); while (!scanner.hasNextInt()) { scanner.nextLine();// consume incorrect values from entire line //or //tastiera.next(); //consume only one invalid token System.out.print("enter number!: "); } // here we are sure that user passed integer int value = scanner.nextInt(); 

循环是正确的想法。 你只需要标记成功并继续:

 boolean inputOK = false; while (!inputOK) { try{ System.out.print("enter number: "); numAb = tastiera.nextInt(); // we only reach this line if an exception was NOT thrown inputOK = true; } catch(InputMismatchException e) { // If tastiera.nextInt() throws an exception, we need to clean the buffer tastiera.nextLine(); } }