检查输入值是否为整数类型java [英] Checking if the input value is integer type java

查看:51
本文介绍了检查输入值是否为整数类型java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在要求用户输入他需要写整数的位置.我设法通过此代码创建验证,以检查该值是否高于所需值,

I am requesting users input where he needs to write integers. I managed to create validation that checks if the value is higher than needed and so, with this code :

int n = sca.nextInt(); 
while (n<=0){
    System.err.println(error_1);
    n = sca.nextInt(); 
}                    

但是现在如何添加字符串检查,我找到了这样的解决方案

But now how to add check for strings, I found such solution How do I keep a Scanner from throwing exceptions when the wrong type is entered?

在实际读取输入之前使用 hasNextInt(),我试图将此检查放在while循环中,并使用 n< = 0 这样在同一位置

That uses hasNextInt() before actually reading the input, I tried to put this check inside while loop in the same place with n<=0 like this

while ( (n<=0)||(sca.hasNextInt() )) {
  ....
}

但是它响应错误,指出变量 n 与该方法不兼容.那么有什么办法可以克服这种情况?

But it responded with error that variable n is not compatible with that method. So is there any way to overcome such thing?

推荐答案

首次调用 nextInt()也会导致异常,如果您不检查输入是否为int 类型.

First invocation of nextInt() also can result in an exception, if you do not check whether the input is of int type.

以下希望可以解决您的问题.

Hope below will resolve your issue.

Scanner sca = new Scanner(System.in);

boolean incorrectInput = true;
int userInput = -1; // initialize as a negative  

while (incorrectInput) {

    if (sca.hasNextInt()) {
        int n = sca.nextInt();
        if (n < 0) {
            System.err.println("error_1");
        } else {
            // do anything else
            userInput = n;
            incorrectInput = false;
        }
    } else {
        sca.next();
    }
}

if (!incorrectInput) {
    System.out.println("UserInput = " + userInput);
}

这篇关于检查输入值是否为整数类型java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆