Reputation: 2894
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.
doSomething()
is hitdoSomethingElse()
is hitdoSomething()
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 ?
Upvotes: 1
Views: 140
Reputation: 1029
You better use some regex e.g. userInput.matches("[0-9]+")
for matching numbers only
Upvotes: 3
Reputation: 35427
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;
}
}
Upvotes: 2
Reputation: 3584
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;
Upvotes: 4