如何循环用户输入直到输入整数?

我是Java的新手,我想继续询问用户输入,直到用户输入一个整数,这样就没有InputMismatchException了。 我已经尝试过这段代码,但是当我输入一个非整数值时,我仍然会遇到exception。

int getInt(String prompt){ System.out.print(prompt); Scanner sc = new Scanner(System.in); while(!sc.hasNextInt()){ System.out.println("Enter a whole number."); sc.nextInt(); } return sc.nextInt(); } 

谢谢你的时间!

使用next而不是nextInt获取输入。 使用try catch来解析使用parseInt方法的输入。 如果解析成功则中断while循环,否则继续。 尝试这个:

  System.out.print("input"); Scanner sc = new Scanner(System.in); while (true) { System.out.println("Enter a whole number."); String input = sc.next(); int intInputValue = 0; try { intInputValue = Integer.parseInt(input); System.out.println("Correct input, exit"); break; } catch (NumberFormatException ne) { System.out.println("Input is not a number, continue"); } } 

更短的解决方案。 只需在sc.next()中输入

  public int getInt(String prompt) { Scanner sc = new Scanner(System.in); System.out.print(prompt); while (!sc.hasNextInt()) { System.out.println("Enter a whole number"); sc.next(); } return sc.nextInt(); } 

使用Juned的代码,我能够缩短它。

 int getInt(String prompt) { System.out.print(prompt); while(true){ try { return Integer.parseInt(new Scanner(System.in).next()); } catch(NumberFormatException ne) { System.out.print("That's not a whole number.\n"+prompt); } } } 

作为替代方案,如果它只是一个整数[0-9],那么你可以检查它的ASCII码。 应该在48-57之间为整数。

在Juned的代码上构建,你可以用if条件替换try块:

  System.out.print("input"); Scanner sc = new Scanner(System.in); while (true) { System.out.println("Enter a whole number."); String input = sc.next(); int intInputValue = 0; if(input.charAt(0) >= 48 && input.charAt(0) <= 57){ System.out.println("Correct input, exit"); break; } System.out.println("Input is not a number, continue"); }