gpt4 book ai didi

java - Double.parseDouble 和 Integer.parseInt 之间的行为差​​异

转载 作者:行者123 更新时间:2023-12-02 03:09:19 26 4
gpt4 key购买 nike

似乎 parseDouble 可以接受带有尾随空格的字符串,但 parseInt 和 parseLong 会抛出异常。

例如对于这个测试用例

@Test
public void testNumberParsing() {
try {
Double.parseDouble("123.0 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
try {
Integer.parseInt("123 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
try {
Long.parseLong("123 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
}

结果是

works
does not work
does not work

为什么会有不同的行为?这是故意的吗?

最佳答案

这种行为实际上已被记录(尽管这是一个非常糟糕的设计......)!

Double.parseDouble :

Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

Double.valueOf :

Leading and trailing whitespace characters in s are ignored. Whitespace is removed as if by the String.trim() method; that is, both ASCII space and control characters are removed.

Integer.parseInt :

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.

关于java - Double.parseDouble 和 Integer.parseInt 之间的行为差​​异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com