我有一个JFrame,我从文本字段获取输入并将其转换为整数。 我也想将它转换为double,如果它是一个double,并且可能会返回一条消息,如果它不是int或double。我怎样才能做到这一点?根据输入将文本输入转换为int或double
我当前的代码:
int textToInt = Integer.parseInt(textField[0].getText());
我有一个JFrame,我从文本字段获取输入并将其转换为整数。 我也想将它转换为double,如果它是一个double,并且可能会返回一条消息,如果它不是int或double。我怎样才能做到这一点?根据输入将文本输入转换为int或double
我当前的代码:
int textToInt = Integer.parseInt(textField[0].getText());
String text = textField[0].getText();
try {
int textToInt = Integer.parseInt(text);
...
} catch (NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(text);
...
} catch (NumberFormatException e2) {
// message?
}
}
为了保持精度,立即解析为BigDecimal。 这parseDouble当然不是语言环境特定的。看到
try {
int textToInt = Integer.parseInt(textField[0].getText());
} catch(NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(textField[0].getText());
} catch(NumberFormatException e2) {
System.out.println("This isn't an int or a double";
}
}
boolean isInt = false;
boolean isDouble = false;
int textToInt = -1;
double textToDouble = 0.0;
try {
textToInt = Integer.parseInt(textField[0].getText());
isInt = true;
} catch(NumberFormatException e){
// nothing to do here
}
if(!isInt){
try {
textToDouble = Double.parseDouble(textField[0].getText());
isDouble = true;
} catch(NumberFormatException e){
// nothing to do here
}
}
if(isInt){
// use the textToInt
}
if(isDouble){
// use the textToDouble
}
if(!isInt && !isDouble){
// you throw an error maybe ?
}
检查如果字符串包含小数点。
if(textField[0].getText().contains("."))
// convert to double
else
// convert to integer
没有必要抛出异常。
在执行上述操作之前,您可以检查字符串是否是使用正则表达式的数字。一种方式是模式[0-9]+(\.[0-9]){0,1}
。我不是最好的正则表达式,所以请纠正我,如果这是错误的。
你可以尝试一系列嵌套的try-渔获物:
String input = textField[0].getText();
try {
int textToInt = Integer.parseInt(input);
// if execution reaches this line, it's an int
} catch (NumberFormatException ignore) {
try {
double textToDouble = Double.parseDouble(input);
// if execution reaches this line, it's a double
} catch (NumberFormatException e) {
// if execution reaches this line, it's neither int nor double
}
}
分析和捕获异常? – VirtualTroll 2013-03-27 12:50:13