I want to know whether the user inputs a char or an int, and hence take a different course of action depending upon the data type.
How to determine numeric Data Type in Java?
523 Views Asked by AudioBubble At
2
There are 2 best solutions below
0
On
try java std parser :
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String inputString = bufferedReader.readLine();
Integer integerValue = getIntegerValueOf(inputString);
if (integerValue == null) {
Double doubleValue = getDoubleValueOf(inputString);
if (doubleValue == null) {
System.out.println("I don't know");
} else {
System.out.println("Congratulation, it's a double : " + doubleValue);
}
} else {
System.out.println("Congratulation, it's a integer : " + integerValue);
}
}
private static Integer getIntegerValueOf(String inputString) {
try {
return Integer.parseInt(inputString);
} catch (NumberFormatException e) {
return null;
}
}
private static Double getDoubleValueOf(String inputString) {
try {
return Double.parseDouble(inputString);
} catch (NumberFormatException e) {
return null;
}
}
You can read line as
Stringand then check string with regex. For example if you are reading fromstdin