[英]Problematic decimalFormat.parse() in Java
有一个要求,如果用户输入一个数字,解析它并doSomething()
。 如果用户输入数字和字符串的混合,则doSomethingElse()
所以,我写了如下代码:
String userInput = getWhatUserEntered();
try {
DecimalFormat decimalFormat = (DecimalFormat)
NumberFormat.getNumberInstance(<LocaleHere>);
Number number = decimalFormat.parse(userInput);
doSomething(number); // If I reach here, I will doSomething
return;
}
catch(Exception e) {
// Oh.. user has entered mixture of alpha and number
}
doSomethingElse(userInput); // If I reach here, I will doSomethingElse
return;
函数getWhatUserEntered()
如下所示
String getWhatUserEntered()
{
return "1923";
//return "Oh God 1923";
//return "1923 Oh God";
}
但有个问题。
doSomething()
被击中doSomethingElse()
被击中doSomething()
被击中。 这是错误的在这里我需要doSomethingElse()
应该被击中。我想要实现的东西有任何内置的(更好的)功能吗? 可以修改我的代码以满足需要吗?
由于特定的 DecimalFormat 实现,一切正常。 JavaDoc 说:
从给定字符串的开头解析文本以生成数字。 该方法可能不会使用给定字符串的整个文本。
因此,您必须将代码修复为以下内容:
String userInput = getWhatUserEntered();
try {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition position = new ParsePosition(0);
Number number = formatter.parse(userInput, position);
if (position.getIndex() != userInput.length())
throw new ParseException("failed to parse entire string: " + userInput, position.getIndex());
doSomething(number); // If I reach here, I will doSomething
return;
}
catch(Exception e) {
// Oh.. user has entered mixture of alpha and number
}
doSomethingElse(userInput); // If I reach here, I will doSomethingElse
return;
您最好使用一些正则表达式,例如userInput.matches("[0-9]+")
仅用于匹配数字
DecimalFormat
接受任何以数字开头的字符串。
您可以做的是执行额外的检查。
try {
DecimalFormat decimalFormat = (DecimalFormat)
NumberFormat.getNumberInstance(<LocaleHere>);
Number number = decimalFormat.parse(userInput);
if (number.toString().equals(userInput)) {
doSomething(number); // If I reach here, I will doSomething
return;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.