Java:检测变量是字符串还是整数

Java:检测变量是字符串还是整数,java,string,Java,String,我正在找人帮我做一点家庭作业。我希望用户输入一个数字字符串,然后将其转换为整数。但是我想做一个循环,检测用户是否输入了错误的值,比如“100”对应的“100” 我当时想做的是这样的事情: do{ numStr = JOptionPane.showInputDialog("Please enter a year in numarical form:" + "\n(Ex. 1995):"); num = Inte

我正在找人帮我做一点家庭作业。我希望用户输入一个数字字符串,然后将其转换为整数。但是我想做一个循环,检测用户是否输入了错误的值,比如“100”对应的“100”

我当时想做的是这样的事情:

    do{
        numStr = JOptionPane.showInputDialog("Please enter a year in numarical form:"
                        + "\n(Ex. 1995):");
        num = Integer.parseInt(numStr);
            if(num!=Integer){
            tryagainstr=JOptionPane.showInputDialog("Entered value is not acceptable."
                                  + "\nPress 1 to try again or Press 2 to exit.");
    tryagain=Integer.parseInt(tryagainstr);
            }
            else{
            *Rest of the code...*
            }
            }while (tryagain==1);
但我不知道如何定义“整数值”。基本上,我想让它看看它是否是一个数字,以防止在用户输入错误内容时崩溃。

尝试以下方法:

    try{
        Integer.valueOf(str);
    } catch (NumberFormatException e) {
        //not an integer
    }

使用正则表达式验证字符串的格式,并仅接受字符串上的数值:

Pattern.matches("/^\d+$/", numStr)
如果
numString
包含有效的数字序列,则
matches
方法将返回
true
,但输入当然可以远远超过
整数的容量。在这种情况下,您可以考虑切换到<代码>长或<代码> BigInteger < /代码>类型。

< P>试试这个

int num;
String s = JOptionPane.showInputDialog("Enter a number please");
while(true)
{
    if(s==null) 
        break; // if you press cancel it will exit
    try {
        num=Integer.parseInt(s);
        break;
    } catch(NumberFormatException ex)
    {
        s = JOptionPane.showInputDialog("Not a number , Try Again");
    }
}

尝试使用
instanceof
,此方法将帮助您在多种类型之间进行检查

范例

如果您只想在整数和字符串之间进行检查,可以使用@NKukhar代码

try{
        Integer.valueOf(str);
    } catch (NumberFormatException e) {
        //not an integer
    }

如果输入不能解析为整数,方法将抛出
NumberFormatException
。您只需使用
try/catch
。谢谢!我现在更了解试一试。我运行了与此类似的操作,当一个变量等于1时,我告诉它执行{try/catch},每次它到达catch时,变量都保持1以保持循环。谢谢
try{
        Integer.valueOf(str);
    } catch (NumberFormatException e) {
        //not an integer
    }