That's not a correct way since Scanner.next() returns a String. If you are looking for primitives or some 'basic' types then you could use an appropriate method like nextByte() or nextBigDecimal().
I.e. with your current implementation you will not ever get to the else if block which checks for Integer.
If you are mostly interested in numbers please check this:
How to check if a String is numeric in Java
lets say String ,int and double only
If performance is not that much of an issue and you are looking for a simplistic solution then I would suggest to go with:
if (isInteger(string)) {
// is an integer
} else if (isDouble(string)) {
// is a double
} else {
// is a string
}
public static boolean isDouble(String string) {
try {
double d = Double.parseDouble(string);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public static boolean isInteger(String string) {
try {
double d = Integer.parseInt(string);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
NOTE: call order matters here, you have to call isInteger() before isDouble() cause integer string is also a double string.