有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Double#parseDouble在尝试解析空子字符串/令牌时不抛出NullPointerException

我正在使用try-catch编写一些代码,在执行Double.parseDouble()(在本例中,我假定它是NullPointerException)时需要空的子字符串来抛出异常

我的问题是,如果我输入类似, , ,(空格逗号空格逗号空格逗号逗号)或类似的内容(如果我理解正确,应该将字符串拆分为三个空格),为什么这段代码不会引发异常:

Scanner input = new Scanner(System.in);
String[] inputParts = null;
String inputLine = input.nextLine();

// the matches() here prevents this from happening, but I still don't understand
// why an exception isn't thrown
if ((inputLine.contains(",") || inputLine.contains(" ")) && !inputLine.matches("\\s+")) { 
    inputParts = inputLine.split("\\s*(,*\\s+)|(,+)");
}

for (int i = 0; i < inputParts.length; ++i) {
    // this prints nothing -- not even a new line. Same behavior even if I don't parseDouble
    // and just print the string directly
    System.out.println(Double.parseDouble(inputParts[i])); 
}

如果我试图从空字符串""" "parseDouble而不这样接受用户输入,它会引发异常

我很困惑为什么会发生这种情况,考虑到我正在处理的代码除了输入类似于上述内容的内容外确实有效(尽管我通过检查每个子字符串是否只有空格并手动抛出相应的异常来修复它)

谢谢


共 (0) 个答案