How do I use Java's Scanner class to determine the datatype of my input?

5.5k Views Asked by At

[sorry if this is a stupid question, I had a lot of trouble wording it for a google search, and couldn't find any answers to the question, even though it'll probably be like a one-line answer]

I'm just following some tutorials on my Java programming course's website.

Right now I'm coding something that takes will open a prompt screen and be like, "Please enter an integer between 5 and 10: ", and scan the number, and do that for a bunch of different variable types, different boundaries, etc.

Super easy stuff. I just have one small question.

How do I tell my scanning method to check that the variable is of type int? I know it's probably really obvious, but if someone enters "A" or "1.543," I'm supposed to have it display, "That is not an integer!" but I don't know how to actually use the scanner to check variable types

2

There are 2 best solutions below

3
On

Firstly, because you want to do validation, just read the input in as a String.

String input = scanner.nextLine();

Then you want to check that it's a number. You can use the parse method, wrapped up in a try catch.

try{
    int inputDbl = Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
    System.out.println("This is not a number");
}

And if you want to do it in a loop, add this try catch to a method that returns a boolean..

public boolean isNumeric(String input)
{
    try{
        double inputDbl = Integer.parseInt(input);
        return true;
    }
    catch(NumberFormatException ex)
    {
        return false;
    }
}
0
On

you can use if(scanner.hasNextInt()){ ... } to see if there is an int next - generally speaking some sequences of characters could be parsed as different types of variables, so you have to use each hasNextDouble(), etc function in the order you desire.

Look here for the complete documentation, which might have many useful functions you are looking for.