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

时间:2016-04-26 12:24:33

标签: java input integer

我希望用户输入80到120之间的整数,没有字母和其他符号。这是我的代码:

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)

谢谢! :)

编辑:谢谢汤姆,得到了解决方案,但我想尝试没有&#34;做&#34;

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

2 个答案:

答案 0 :(得分:0)

您的循环条件错误。只要输入中没有可用的整数,就检查&#34;类似于读取整数&#34;。那会失败

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

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

您正在使用hasNextInt检查一次int是否可用,但之后您读取了两次值!

答案 1 :(得分:0)

    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循环看看我的代码