我要做的是获取String
输入,并将其解析为双精度或整数。
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
这样,您可以确保仅通过解析双精度数不会丢失整数精度(双精度数的可能值范围与整数不同),并且您可以处理既没有输入有效整数也没有输入双精度数的情况。
如果块内的代码抛出异常,try
则执行 catch 块中的代码。在我们的例子中,如果方法抛出异常parseInt()
,我们会在第二个 try 块所在的 catch 块中执行代码。如果方法抛出异常 parseDouble()
,那么我们执行第二个 catch 块内的代码,它会打印一条错误消息。