我有一个存储数字的字符串。现在我想解析该字符串并获取浮点数。
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
try {
System.out.println(Integer.parseInt(" 2 "));
} catch(NumberFormatException e) {
System.out.println("Exception caught");
}
System.out.println(Float.parseFloat(" 2.4 "));
}
}
现在在上面的代码中如果你运行它就会成功。我的问题是,为什么在整数的情况下尾随空格会抛出一个NumberFormatException
解析浮点数时不会抛出浮点数?
PS:布尔和双重解析的情况也是如此。
PPS:为什么java中存在不一致?我已经检查了源代码
正如您在相关源代码中看到的,该值将被修剪:
static FloatingDecimal.ASCIIToBinaryConverter readJavaFormatString(String arg) throws NumberFormatException {
boolean arg0 = false;
boolean arg1 = false;
try {
arg = arg.trim();
....
因此,在转换为 floatValue 之前,将删除空格。
更多信息请参见源代码浮点小数这是由Float.class
.
Integer.parseInt()
不要修剪字符串值:
public static int parseInt(String arg, int arg0) throws NumberFormatException {
if (arg == null) {
throw new NumberFormatException("null");
} else if (arg0 < 2) {
throw new NumberFormatException("radix " + arg0 + " less than Character.MIN_RADIX");
} else if (arg0 > 36) {
throw new NumberFormatException("radix " + arg0 + " greater than Character.MAX_RADIX");
} else {
int arg1 = 0;
boolean arg2 = false;
int arg3 = 0;
int arg4 = arg.length();
int arg5 = -2147483647;
if (arg4 > 0) {
char arg8 = arg.charAt(0);
if (arg8 < 48) {
if (arg8 == 45) {
arg2 = true;
arg5 = MIN_VALUE;
} else if (arg8 != 43) {
throw NumberFormatException.forInputString(arg);
}
if (arg4 == 1) {
throw NumberFormatException.forInputString(arg);
}
++arg3;
}
int arg7;
for (int arg6 = arg5 / arg0; arg3 < arg4; arg1 -= arg7) {
arg7 = Character.digit(arg.charAt(arg3++), arg0);
if (arg7 < 0) {
throw NumberFormatException.forInputString(arg);
}
if (arg1 < arg6) {
throw NumberFormatException.forInputString(arg);
}
arg1 *= arg0;
if (arg1 < arg5 + arg7) {
throw NumberFormatException.forInputString(arg);
}
}
return arg2 ? arg1 : -arg1;
} else {
throw NumberFormatException.forInputString(arg);
}
}
}
这就是为什么你会在那里得到异常
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)