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

时间:2019-01-26 23:13:25

标签: java int

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

这是我的代码:

    $('#anyQuestion').validate({
    rules: {
        name: {
            required: true
        },
        email: {
            required: true,
            email: true
        },
        phone: {
            required: true,
             minlength: 10
        }
    },
    submitHandler: function () {
        var anyQuestionForm = $('#anyQuestion');
        anyQuestionForm.submit(function (e) {
            // e.preventDefault();
            $.ajax({
                type: 'post',
                url: '/xhr/anyquestion',
                data: anyQuestionForm.serialize(),
                success: function (data) {
                    if( data == 'ok' ){
                       Swal.fire({
                           position: 'top-end',
                           type: 'success',
                           showConfirmButton: false
                         })
                       console.log(data);
                       document.getElementById("anyQuestion").reset();
                    }
                },
                error: function (data) {
                    Swal.fire({
                        type: 'error',
                      })
                },
            });
         });
    }
});

我已经尝试过了,对于如下输入:34443 22123 cdsfr4d,它显示错误(表示正常工作),但是当我只给出2或3个整数时:34或567,则不会显示任何错误!我如何对其进行管理以便向我显示正确的消息

3 个答案:

答案 0 :(得分:0)

删除&& input.hasNextByte()

答案 1 :(得分:0)

我假设您只希望用户输入: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语句的更多信息: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

欢迎使用Stack Overflow社区,请确保在使用Stack之前先使用Google!

答案 2 :(得分:0)

我不确定您想做什么。但是按照您的方法,似乎您想通过键盘输入一个数字,并希望检查它是否是一个数字。如果我是对的,那么我们开始吧。

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。

相关问题