Java: Detecting If a Variable Is a String or an Integer

Java: Detecting If a Variable Is a String or an Integer

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.

1

4 Answers

Try this:

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

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
    }

try this

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");
    }
}
1

Use a regex to validate the format of the string, and accept only numeric values on it:

Pattern.matches("/^\d+$/", numStr)

The matches method will return true if numString contains a valid numeric sequence, but of course the input can be way above an Integer's capacity. In that case, you can consider switching to a long or a BigInteger type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.