学习《21天学通java(第7版)》之错误收集

parseInt()用法

2018年11月27日

按照课本敲了一段很简单的代码竟然出现错误了。编译程序出现错误如下:

Exception in thread “main” java.lang.NumberFormatException: For input string: “9.99”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at org.cadenhead.ecommerce.Item.(Item.java:14)
at org.cadenhead.ecommerce.Storefront.addItem(Storefront.java:9)
at org.cadenhead.ecommerce.GiftShop.main(GiftShop.java:9)
构建失败 (总时间: 0 秒)

根据错误提示,是parseInt()用法错误,定位代码

Item(String idIn, String nameIn, String retailIn, String qIn){
        id = idIn;
        name = nameIn;
        retail = Double.parseDouble(retailIn);
        quantity = Integer.parseInt(qIn);
        if (quantity > 400)
            price = retail * .5D;
        else if (quantity > 200)
            price = retail * .6D;
        else 
            price = retail * .7D;
        price = Math.floor(price * 100 + .5) /100;
                           
    }

粗略看,quantity = Integer.parseInt(qIn);是没有问题的,那就是参数传输错误。通过查看parseInt()说明,发现问题了。是把“9.99”中“.”的存在导致的异常。因为,parseInt()方法只能十进制的字符串。

JDK文档中对parseInt()说明如下:

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign ‘-’ (’\u002D’) to indicate a negative value or an ASCII plus sign ‘+’ (’\u002B’) to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值