Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Detecting if a variable is a String or an Integer

Tags:

java

string

I'm look for some help on a bit of homework I have. I want the user to enter a numerical String, then convert it to an Integer. But I want to make a loop that will detect if the user entered in the wrong value such as "One Hundred" as apposed to "100".

What I was thinking was to do something like this:

    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);

But I don't know how to define that "Integer" value. I essentially want it to see if it is a number or not to prevent it from crashing if the user enters the wrong thing.

like image 881
Dave555 Avatar asked Nov 16 '25 02:11

Dave555


1 Answers

Try use instanceof , this method will help you with check between many types

Example

if (s instanceof String ){
// s is String
}else if(s instanceof Integer){
// s is Integer value
}

If you want just check between integer and string you can use @NKukhar code

try{
        Integer.valueOf(str);
    } catch (NumberFormatException e) {
        //not an integer
    }
like image 134
Mina Fawzy Avatar answered Nov 18 '25 18:11

Mina Fawzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!