Java:检测变量是String还是Integer

Dav*_*555 2 java string

我正在为我的一些家庭作业寻求帮助.我希望用户输入数字字符串,然后将其转换为整数.但我想制作一个循环来检测用户是否输入了错误的值,例如"One Hundred"为"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);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何定义"整数"值.我基本上希望它看看它是否是一个数字,以防止它在用户输入错误的东西时崩溃.

Min*_*wzy 8

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

例子

if (s instanceof String ){
// s is String
}else if(s instanceof Integer){
// s is Integer value
}
Run Code Online (Sandbox Code Playgroud)

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

try{
        Integer.valueOf(str);
    } catch (NumberFormatException e) {
        //not an integer
    }
Run Code Online (Sandbox Code Playgroud)


nku*_*har 5

试试这个:

    try{
        Integer.valueOf(str);
    } catch (NumberFormatException e) {
        //not an integer
    }
Run Code Online (Sandbox Code Playgroud)