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

标签 java

似乎 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/

相关文章:

java - Selenium WebDriver 代码无法跟踪窗口中没有标题或 URL 的元素

java - 没有 Alpha channel 的 PNG 透明度

javascript - 响应 header 为空

java - 构建 Eclipse 项目时自动运行 JUnit

java - Android下载文件内存不足问题

java - 数据库会被这段代码命中两次吗?

java - 如何让循环在我的 Java 程序中工作?

java - 如何将 Siddhi CEP 的依赖项添加到我的 pom.xml 文件中?

java - 即使在删除工作目录后,Tomcat 也会重新编译旧版本的 JSP

eclipse - 在 eclipse 3.1.2 中创建 java 项目 - JRE 版本是否正确?