2013-08-01 25 views
-1

我基本上想要以下while循环来检查输入是否是一个整数。它不能包含小数,因为它指向一个数组。如果输入的值是小数,它应该再次提示用户。问题是我在while循环以这段代码开始之前得到两个提示。有任何想法吗?检查如果从扫描仪输入是int与while循环java

 System.out.print("Enter month (valid values are from 1 to 12): "); 
    Scanner monthScan = new Scanner(System.in); 
    int monthInput = monthScan.nextInt(); 
    // If the month input is below 1 or greater than 12, prompt for another value 
    while(monthInput<1 || monthInput>12 || !monthScan.hasNextInt()) 
    { 
     System.out.print("Invalid value! Enter month (valid values are from 1 to 12): "); 
     monthInput = new Scanner(System.in).nextInt(); 
    } 

感谢

编辑:电流输出提供了以下:

Enter month (valid values are from 1 to 12): 2 
2 

注意我是如何进入2甚至两次虽然这是一个有效的值。

回答

1

一个小的修改程序解决问题

System.out.print("Enter month (valid values are from 1 to 12): "); 
     Scanner monthScan = new Scanner(System.in); 
     int monthInput = monthScan.nextInt(); 
     // If the month input is below 1 or greater than 12, prompt for another value 
     while((monthInput<1 || monthInput>12)) 
     { 
      System.out.print("Invalid value! Enter month (valid values are from 1 to 12): "); 

      monthInput = monthScan.nextInt(); 
     } 
     System.out.println("I am here"); 

输出:

Enter month (valid values are from 1 to 12): -5 
Invalid value! Enter month (valid values are from 1 to 12): -5 
Invalid value! Enter month (valid values are from 1 to 12): -2 
Invalid value! Enter month (valid values are from 1 to 12): 5 
I am here 

希望这有助于你。

2

您可以将您的逻辑之后检查这样

System.out.print("Enter month (valid values are from 1 to 12): "); 
Scanner monthScan = new Scanner(System.in); 

while(monthScan.hasNext()) 
{ 
    if(!monthScan.hasNextInt() && (monthInput<1 || monthInput>12)) 
    { 
     System.out.print("Invalid value! Enter month (valid values are from 1 to 12):"); 
     continue; 
    } 

    // If the month input is below 1 or greater than 12, prompt for another value 
    int monthInput = monthScan.nextInt(); 
    //do your logic here 
    break;//use the break after logic 

} 

更新
使用break,使其有效输入后退出。

+0

不起作用。无论输入是否有效,我最终都会得到无限循环的提示。 – Mo2

+0

@ Mo2更新请看看 – Prabhaker

3

在您致电nextInt()之前,请检查输入是否为整数,并使用hasNextInt()。否则当用户输入一个非整数时,nextInt()将抛出一个InputMismatchException

int monthInput; 

System.out.print("Enter month (valid values are from 1 to 12): "); 
Scanner monthScan = new Scanner(System.in); 

if (monthScan.hasNextInt()) { 
    monthInput = monthScan.nextInt(); 
} else { 
    monthScan.next(); // get the inputted non integer from scanner 
    monthInput = 0; 
} 

// If the month input is below 1 or greater than 12, prompt for another value 
while (monthInput < 1 || monthInput > 12) { 
    System.out.print("Invalid value! Enter month (valid values are from 1 to 12): "); 
    if (monthScan.hasNextInt()) { 
     monthInput = monthScan.nextInt(); 
    } else { 
     String dummy = monthScan.next(); 
     monthInput = 0; 
    } 
}