What I would do is get String
input, and parse it as either a double or an integer.
String str = input.next();
int i = 0;
double d = 0d;
boolean isInt = false, isDouble = false;
try {
// If the below method call doesn't throw an exception, we know that it's a valid integer
i = Integer.parseInt(str);
isInt = true
}catch(NumberFormatException e){
try {
// It wasn't in the right format for an integer, so let's try parsing it as a double
d = Double.parseDouble(str);
isDouble = true;
}catch(NumberFormatException e){
// An error was thrown when parsing it as a double, so it's neither an int or double
System.out.println(str + " is neither an int or a double");
}
}
// isInt and isDouble now store whether or not the input was an int or a double
// Both will be false if it wasn't a valid int or double
This way, you can ensure that you don't lose integer precision by just parsing a double (doubles have a different range of possible values than integers), and you can handle the cases where neither a valid integer or double was entered.
If an exception is thrown by the code inside the try
block, the code in the catch block is executed. In our case, if an exception is thrown by the parseInt()
method, we execute the code in the catch block, where the second try-block is. If an exception os thrown by the parseDouble()
method, then we execute the code inside the second catch-block, which prints an error message.
String
would be best. Then, you'll need to verify that the given number is a number. If it contains a dot, or comma and the left and right part are numeric, then it is adouble
. Else if there is no dot or comma but the rest is numeric, it is anint
. For checking if it is a double you can use this regex: "-?\\d+(\\.\\d+)?", for numbers you can use "[0-9]*". – Namely