对于循环 - 验证输入,程序崩溃(.hasNextInt())

时间:2015-03-01 21:51:36

标签: java validation for-loop input

我在java中编写一个程序,用户使用for循环添加5个数字(正整数)。 我已经设法在给出正确的输入时使其工作,甚至在给出负整数时,但是当输入非int时程序崩溃。 任何帮助表示赞赏!

    for (int i = 0; i < 5 ; i++ ) {
        if (myScanner.hasNextInt()) {
            x = myScanner.nextInt();
            if (x < 0) {
               System.out.println("Invalid input, enter again:"); 
               x = myScanner.nextInt();
            }
        } 
        else {
            System.out.println("Invalid input, enter again:");
            x = myScanner.nextInt();// this works in the nested if but not here,  why?

        }
        sum += x;
    }

    System.out.println("Sum is: " + sum);
}//end class

2 个答案:

答案 0 :(得分:0)

你检查扫描仪是否有下一个整数,然后再检查一个它没有的整数......

以下是更正后的版本:

for (int i = 0; i < 5 ; i++ ) {
    if (myScanner.hasNextInt()) {
        x = myScanner.nextInt();
        if (x < 0) {
           System.out.println("Invalid input, enter again:"); 
        } else {
           sum += x;
        }
    } 
    else {
        // get whatever is on the scanner, since we know it isn't and int
        String crud  = s.next(); 
        System.out.println("Invalid input "+crud+" enter again:");
    }

}

答案 1 :(得分:0)

抛出InputMismatchException,尝试从一个地方调用x = myScanner.nextInt的逻辑,

int count = 0;
 while (true) 
 {
   try
   {
     if (myScanner.hasNextInt()) 
     {
       x = myScanner.nextInt();
       if (x < 0) 
       {
         System.out.println("Invalid input, enter again:"); 
       }
     } 
     else 
     {
        System.out.println("Invalid input, enter again:");
        continue;
     }
   }
   catch(Exception e)
   {
      System.out.println("Invalid input, enter again:"); 
      continue;
   }
   count++;
   sum += x;
   if(count==5)break;
 }