Java 如何检查用户输入是否为1整数

Java 如何检查用户输入是否为1整数,java,int,Java,Int,我要求用户输入一个数字,我需要检查用户的答案是否只有一个整数 这是我的代码: System.out.println("MENU:What do you want to do ? \n1.Buy a new ticket!\n2.Renewal of a ticket\n3.Update the content"); System.out.println("Type the number of what you want to do "); if

我要求用户输入一个数字,我需要检查用户的答案是否只有一个整数

这是我的代码:

System.out.println("MENU:What do you want to do ? \n1.Buy a new ticket!\n2.Renewal of a ticket\n3.Update the content");
            System.out.println("Type the number of what you want to do ");

            if (!(input.hasNextInt() && input.hasNextByte())) {   // if the input is not an integer and more than one byte 
                System.out.println("ERROR!!Enter an integer value ");
                input.next();
            } else {

                int Read = input.nextInt(); //reads what the user has typed/given
 System.out.println("You entered an integer value! ");
            }

我已经试过了,它显示了输入的错误(它正在工作):34443 22123 cdsfr4d,但当我只给出2或3个整数,如:34或567,它不会显示任何错误!为了显示正确的消息,我如何对其进行设置?删除
&&input.hasNextByte()

我假设您只希望用户输入:1、2或3,因为这是我在控制台菜单中看到的

我处理这个问题的方法是使用switch语句和默认大小写,以防它们输入任何其他内容

if (!(input.hasNextInt()) {   // if the input is not an integer and more than one 
    System.out.println("ERROR!!Enter an integer value ");
    input.next();
} else {

    int choice = input.nextInt();

    switch (choice) {
        case 1: //If choice is 1

        case 2: // If choice is 2

        case 3: // If choice is 3

        default: // If choice is any other integer
    }

}

Switch语句在Java中并不常用,因为通常有更好的方法来处理这些场景。以下是有关switch语句的更多信息:


欢迎来到Stack Overflow社区,确保在使用Stack之前使用Google

我不知道你想做什么。但根据您的方法,似乎您希望通过键盘输入一个数字,并希望检查它是否为一位数。如果我是对的,那我们走吧

public class Tests1 {
public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number");
    int number = sc.nextInt();
    Tests1 obj1=new Tests1();
    System.out.println(obj1.digit(number));
}
    public boolean digit(int num) {
        int count = 0;
        while (num != 0) {
            num = num / 10;
            count++;
        }
        if (count == 1) {
            return true;
        }
        return false;
    }
} 

我的代码检查数字是否为个位数。如果是一位数字,则返回true,否则返回false。

问题:为什么要检查整数,而不仅仅是检查
1
2
3
22123
abcd
一样错误。我将读取该行(作为字符串)并检查它是否是有效选项之一(在允许重新键入{until correct}的循环中),它不起作用为什么不起作用?除了这三个值之外,接受任何东西都是正确的吗???您应该使用
Switch语句来实现这一点。如何使用Switch?