This question already has an answer here:
Parsing float stored as string should throw Exception

(1个答案)


3年前关闭。




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



Double.valueOf :



Integer.parseInt :

09-30 17:58