我有一个 JFrame,我从文本字段中获取输入并将其转换为整数。如果它是双精度数,我还想将它转换为双精度数,如果它既不是整数也不是双精度数,我可能会返回一条消息。我怎样才能做到这一点?
我当前的代码:
int textToInt = Integer.parseInt(textField[0].getText());
我有一个 JFrame,我从文本字段中获取输入并将其转换为整数。如果它是双精度数,我还想将它转换为双精度数,如果它既不是整数也不是双精度数,我可能会返回一条消息。我怎样才能做到这一点?
我当前的代码:
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-catch:
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
}
}