如何避免java中的数字格式异常? [英] How to avoid Number Format Exception in java?

查看:183
本文介绍了如何避免java中的数字格式异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的日常Web应用程序开发中,有许多情况我们需要从用户那里获取一些数字输入。

In my day to day web application development there are many instances where we need to take some number inputs from the user.

然后将此数字输入传递给应用程序的服务或DAO层。

Then pass on this number input to may be service or DAO layer of the application.

在某个阶段,因为它是一个数字(整数或浮点数),我们需要将它转换为Integer,如下面的代码片段所示。

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?

推荐答案

抓住你的异常并进行适当的异常处理:

Just catch your exception and do proper exception handling:

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());
        }
    }

这篇关于如何避免java中的数字格式异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆