2017-05-09 77 views
-5

我是编程的noob。 我想写一个编码的代码,要求用户输入值,直到输入一个整数。要求用户输入值,直到输入整数

public class JavaApplication34 { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 

     int flag = 0; 
     while(flag == 0) { 
      int x = 0; 
      System.out.println("Enter an integer"); 

      try { 
       x = sc.nextInt(); 
       flag = 1; 
      } catch(Exception e) { 
       System.out.println("error");   
      } 

      System.out.println("Value "+ x); 
     } 
    } 
} 

我认为的代码是正确的,它应该问我,如果我已经进入不是整数以外的任何重新输入值。 但是,当我运行它,并说我输入xyz 它迭代无限时间没有要求我输入值。

test run : 
Enter an integer 
xyz 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
Enter an integer 
error 
Value 0 
+1

在一个catch块中,比如你的catch(Exception e){'',''e''拥有关于发生了什么的宝贵信息。使用''e.printStackTrace()''来了解更多。 – f1sh

+6

你的'flag'很伤心,因为它想成为布尔值。 – dly

+0

为什么?请帮助 –

回答

2

在错误的情况下,你需要清除你输入的字符串(例如,通过nextLine)。由于它不能被nextInt返回,它仍然在扫描仪中。您还希望将输出值的行移动到try,因为当出现错误时您不希望这样做。

东西沿着这些路线:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    int flag = 0; 
    while(flag == 0) 
    { 
     int x = 0; 
     System.out.println("Enter an integer"); 
     try 
     { 
      x = sc.nextInt(); 
      flag = 1; 
      System.out.println("Value "+ x); 
     } 
     catch (Exception e){ 
      System.out.println("error"); 
      if (sc.hasNextLine()) { // Probably unnecessary 
       sc.nextLine(); 
      } 
     } 
    } 
} 

边注:Java有boolean,就没有必要使用int为标志。所以:

boolean flag = false; 

while (!flag) { 

flag = true; // When you get a value 
+0

你能帮忙吗? –

+2

@MridulMittal:**是**帮助。 –

+0

请帮我看看代码我是一个noob –

5

当扫描器抛出InputMismatchException时,扫描仪将无法 传递导致该异常的标记。

因此sc.nextInt()再次读取相同的标记并再次抛出相同的异常。

... 
... 
... 
catch(Exception e){ 
    System.out.println("error"); 
    sc.next(); // <---- insert this to consume the invalid token 
} 
2

你可以改变你的逻辑如下图所示:

int flag = 0; 
    int x = 0; 
    String str=""; 
    while (flag == 0) {   
     System.out.println("Enter an integer"); 
     try { 
      str = sc.next(); 
      x = Integer.parseInt(str); 
      flag = 1; 
     } catch (Exception e) { 
      System.out.println("Value " + str); 
     }   
    } 

在这里,我们第一次读到来自扫描仪的输入,然后我们正试图解析它如int,如果输入的不是整数值,那么它会抛出异常。在例外情况下,我们正在打印用户输入的内容。当用户输入一个整数时,它将被成功解析,并且标志值将更新为1,并且会导致循环退出。

0

this问题的答案可以帮助你

它利用扫描仪的.hasNextInt()功能!

相关问题