This question already has an answer here:
In my day to day web application development there are many instances where we need to take some number inputs from the user.
Then pass on this number input to may be service or DAO layer of the application.
At some stage since its a number (integer or float), we need to convert it into Integer as shown in the following code snippet.
String cost = request.getParameter("cost");
if (cost !=null && !"".equals(cost) ){
Integer intCost = Integer.parseInt(cost);
List<Book> books = bookService . findBooksCheaperThan(intCost);
}
Here in the above case I have to check if the input is not null or if there is no input (blank) or sometimes there is a possibility of a non number inputs e.g. blah, test etc.
What is the best possible way of handling such situations?
As always, the Jakarta Commons have at least part of the answer :
NumberUtils.isNumber()
This can be used to check most whether a given String is a number. You still have to choose what to do in case your String isnt a number ...
That depends on your environment. JSF for example would take the burden of manually checking and converting Strings <-> Numbers from you, Bean Validation is another option.
What you can do immediately in the snippet you provide:
getAsInt(String param)
, in it:String.isEmpty()
(Since Java 6),try / catch
What you should definitely think about if you happen to write a lot of code like this:
(This would be interceptor-based).
Last but not least: Save the work and try to switch to a framework which gives you support for these common tasks...
Try to convert Prize into decimal format...
You can avoid the unpleasant looking try/catch or regex by using the Scanner class:
one posibility: catch the exception and show an error message within the user frontend.
edit: add an listener to the field within the gui and check the user inputs there too, with this solution the exception case should be very rare...
Documentation for the method from the Apache Commons Lang (from here):
isNumber
from java.org.apache.commons.lang3.math.NumberUtils:[code is under version 2 of the Apache License]