java.lang.NumberFormatException: For input string: “10.0”

只谈情不闲聊 提交于 2020-08-25 04:18:08

问题


This code must validate input data from the findActions() method:

try {
    System.out.println(findActions(lookingArea.substring(0, right)));// always printing valid number string
    Integer.parseInt(findActions(lookingArea.substring(0, right)));// checking for number format
}
catch(NumberFormatException exc) {
    System.out.println(exc);
}

But I always have java.lang.NumberFormatException: For input string: "*number*" that is so strange, because checking with System.out.println(findActions(lookingArea.substring(0, right)));,

I get *number* like 10.0


回答1:


Integer.parseInt doesn't expect the . character. If you're sure it can be converted to an int, then do one of the following:

  1. Eliminate the ".0" off the end of the string before parsing it, or
  2. Call Double.parseDouble, and cast the result to int.

Quoting the linked Javadocs above:

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.




回答2:


10.0 is not an integer number. Instead, you can use:

int num = (int) Double.parseDouble(...);


来源:https://stackoverflow.com/questions/19303351/java-lang-numberformatexception-for-input-string-10-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!