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.