简体   繁体   中英

Problematic decimalFormat.parse() in Java

There is a requirement that if user enters a number, parse it and doSomething() . If user enters a mixture of number and string, then doSomethingElse()

So, I wrote the code as under:

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;

The function getWhatUserEntered() looks as under

String getWhatUserEntered()
{
  return "1923";
  //return "Oh God 1923";
  //return "1923 Oh God";
}

But, there is a problem.

  • When user enters 1923 --> doSomething() is hit
  • When user enters Oh God 1923 --> doSomethingElse() is hit
  • When user enters 1923 Oh God --> doSomething() is hit. This is wrong Here I need that doSomethingElse() should be hit.

Is there any inbuilt (better) function to the thing I want to achieve ? Can my code be modified to suit needs ?

Everything is OK due to specific DecimalFormat implementation. JavaDoc says:

Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

So you have to fix your code to something like this:

  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 accepts any string if it starts with a number.

What you can do is perform an additional check.

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM