2013-10-02 105 views
3

我是新来的Java,我想继续询问用户输入,直到用户输入一个整数,这样就没有InputMismatchException。我试过这段代码,但是当我输入一个非整数值时,我仍然会得到异常。如何循环用户输入,直到输入整数?

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(); 
} 

谢谢你的时间!

回答

3

在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

使用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"); 
      } 
     } 
+0

谢谢!我想知道,有没有比这更短的方式? – Shail

+0

@ Shail可能有更好的解决方案,但这是我可以用我有限的能力创造的解决方案。如果有帮助,请接受答案。谢谢! –

+0

谢谢。它为我工作。 –

0

作为替代,如果它仅仅是一个单一的数字整数[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"); 
    } 
4

较短的解决方案。只需输入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(); 

} 
相关问题