1

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 ?

SimpleGuy
  • 2,764
  • 5
  • 28
  • 45

3 Answers3

4

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;
Ιναη ßαbαηιη
  • 3,410
  • 3
  • 20
  • 41
3

You better use some regex e.g. userInput.matches("[0-9]+") for matching numbers only

gapvision
  • 999
  • 1
  • 10
  • 30
2

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;
  }
}
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137