有问题的十进制格式。Java中的parse()
有一个要求,如果用户输入一个数字,解析它并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";
}
但是,有一个问题
- 当用户输入1923时
doSomething()
被击中 - 当用户进入哦,上帝1923-->
doSomethingElse()
被击中 - 当用户进入1923年时,哦,上帝
doSomething()
被击中。这是错误的 这里我需要doSomethingElse()
应该被点击李>
我想实现的东西有没有内在的(更好的)功能? 我的代码可以根据需要修改吗
# 1 楼答案
您最好使用一些正则表达式,例如
userInput.matches("[0-9]+")
只用于匹配数字# 2 楼答案
由于具体的DecimalFormat实现,一切正常。JavaDoc说:
因此,您必须将代码修改为以下内容:
# 3 楼答案
DecimalFormat
接受任何以数字开头的字符串您可以做的是执行额外的检查