如何检查用户是否输入2个数字之间的整数?

如何检查用户是否输入2个数字之间的整数?

问题描述:

我希望用户输入80到120之间的整数,没有字母和其他符号。这里是我的代码:如何检查用户是否输入2个数字之间的整数?

import java.util.*; 

public class Test {  

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

//checking for integer input 
    while (!in.hasNextInt()) 
    { 
     System.out.println("Please enter integers between 80 and 120."); 
     in.nextInt(); 
     int userInput = in.nextInt(); 

//checking if it's within desired range 
     while (userInput<80 || userInput>120) 
     { 
      System.out.println("Please enter integers between 80 and 120."); 
      in.nextInt(); 
     } 
    } 
} 

}

不过,我面临的一个错误。有针对这个的解决方法吗?

Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Unknown Source) 
at java.util.Scanner.next(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at Array.main(Array.java:15) 

谢谢! :)

编辑:谢谢汤姆,得到了解决,但想尝试没有“做”

Scanner in = new Scanner(System.in); 

    int userInput; 
    do { 
    System.out.println("Please enter integers between 80 and 120."); 
    while (!in.hasNextInt()) 
    { 
     System.out.println("That's not an integer!"); 
     in.next(); 
     } 
     userInput = in.nextInt(); 
} while (userInput<81 || userInput >121); 

System.out.println("Thank you, you have entered: " + userInput); 
} 
} 
+0

当然有!抓住java.util.InputMismatchException并适当处理它。出于兴趣,你为什么要跳过输入? – Bathsheba

+0

@Bathsheba你好,我想这样做没有使用捕捉,因为我正在修改我的学校工作,这只是前几个主题(在这一点上没有学到异常) – Ken

+0

将条件改为while (in.hasNextInt()) – Unknown

你的循环条件是错误的。你可以检查“只要输入中没有可用整数:读取一个整数”。这是失败

另外:你打电话nextInt两次。不要这样做。删除第一个电话:

System.out.println("Please enter integers between 80 and 120."); 
in.nextInt(); //REMOVE THIS LINE 
int userInput = in.nextInt(); 

如果int可以使用hasNextInt要检查一次,但你读值的两倍!

+0

我试过了,仍然收到相同的错误。 – Ken

+0

是的,我尝试删除它,我仍然有同样的错误D: – Ken

+1

'while(!in.hasNextInt())'也许你的问题在这里。 –

boolean continueOuter = true; 

    while (continueOuter) 
     { 
      System.out.println("Please enter integers between 80 and 120."); 
      String InputVal = in.next(); 

     try { 
      int input = Integer.parseInt(InputVal); 
       //checking if it's within desired range 
      if(FirstInput>80 && FirstInput<120) 
      { 
       //no need to continue got the output 
       continueOuter = false; 
      }else{ 
        System.out.println("Please enter integers between 80 and 120."); //need to continue didnt got the exact output 
       continueOuter = true;  
      } 

     } catch (Exception e) { 
     //not an int  
     System.out.println(InputVal); 
     continueOuter = true; 
     } 
} 

在这段代码中,我已经创建了一个布尔值来检查程序是否想继续执行。如果用户输入了有效值,程序将停止 ,但是您可以根据需要更改该值。你不需要两个while循环我已经改变了内部while循环到if循环看看我的代码

+1

'continue = false'?在Java中祝好运。 – Bathsheba

+0

我指的是continueouter,这是一个错误。 – Priyamal

+0

@priyamal你好,如果用户输入一个字符呢?我头人物是指数字或其他东西。 – Ken