如何避免java中的数字格式异常?

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)

  • +1:最后一个明智的答案.我唯一要改变的是在try块之外调用`bookService`,因为这个特殊的异常仅适用于解析`cost`字符串. (2认同)