Jake Hansen
Jake Hansen

Reputation: 63

How to check if a String is a valid int or double

I am trying to determine if a user's input contains a valid int or double instead of a valid String. If the input is an int or a double the program should state "Invalid make".

Here is my code:

else if (tokens[0].equals("make"))
{
  if (!tokens[2].equals(String)) System.out.println("     Invalid make");
  // I have 5 spaces above because I don't know how to use printf with strings
  searchByMake(tokens[2]);
}

Edit: Sorry for the confusion guys.. "tokens[]" is an array of strings.

I am trying to get my program to print "Invalid Make" if the user inputs make = number (when number is tokens[2])

Upvotes: 3

Views: 13458

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could write a function to test it by calling Double.parseDouble(String) and catching the NumberFormatException (this will handle double and int values) when it isn't like

public static boolean isNumber(String str) {
    try {
        double v = Double.parseDouble(str);
        return true;
    } catch (NumberFormatException nfe) {
    }
    return false;
}

Then you could call it like

if (isNumber(tokens[2])) {
  System.out.println("     Invalid make");
}

And the printf with String might look like,

String msg = "Invalid make";
System.out.printf("     %s%n", msg);

Upvotes: 6

    public static boolean isInteger(String s) {
        try { 
            Integer.parseInt(s); 
        } catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }

public static boolean isInteger(String s) {
    return isInteger(s);
}

and for double too..

Upvotes: 0

You can use instanceof

if(tokens[2] instanceof String) ....
else if(tokens[2] instanceof Double) ....

Upvotes: -2

Related Questions