[英]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.