ash*_*ram 14 java numberformatexception
在我的日常Web应用程序开发中,有许多情况需要从用户那里获取一些数字输入.
然后传递此数字输入可以是应用程序的服务或DAO层.
在某个阶段,因为它是一个数字(整数或浮点数),我们需要将它转换为Integer,如下面的代码片段所示.
String cost = request.getParameter("cost");
if (cost !=null && !"".equals(cost) ){
Integer intCost = Integer.parseInt(cost);
List<Book> books = bookService . findBooksCheaperThan(intCost);
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我必须检查输入是否为空或是否没有输入(空白)或有时可能存在非数字输入,例如,等等,测试等.
处理此类情况的最佳方法是什么?
Rof*_*ion 27
抓住您的异常并进行适当的异常处理:
if (cost !=null && !"".equals(cost) ){
try {
Integer intCost = Integer.parseInt(cost);
List<Book> books = bookService . findBooksCheaperThan(intCost);
} catch (NumberFormatException e) {
System.out.println("This is not a number");
System.out.println(e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107444 次 |
| 最近记录: |