java.lang.NumberFormatException:对于输入字符串:“10.0”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19303351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:53:03  来源:igfitidea点击:

java.lang.NumberFormatException: For input string: "10.0"

javaexceptionnumberformatexception

提问by George

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

此代码必须验证来自 findActions() 方法的输入数据:

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)));,

但我总是java.lang.NumberFormatException: For input string: "*number*"觉得这很奇怪,因为检查System.out.println(findActions(lookingArea.substring(0, right)));

I get *number*like 10.0

我得到*number*像 10.0

采纳答案by rgettman

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

Integer.parseInt不期待这个.角色。如果您确定可以将其转换为int,请执行以下操作之一:

  1. Eliminate the ".0"off the end of the string before parsing it, or
  2. Call Double.parseDouble, and cast the result to int.
  1. ".0"在解析之前消除字符串的末尾,或者
  2. 调用Double.parseDouble,并将结果转换为int

Quoting the linked Javadocs above:

引用上面链接的 Javadocs:

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.

字符串中的字符必须都是十进制数字,除了第一个字符可以是 ASCII 减号 '-' ('\u002D') 表示负值或 ASCII 加号 '+' ('\u002B')表示正值。

回答by Eng.Fouad

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

10.0不是整数。相反,您可以使用:

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