有 Java 编程相关的问题?

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

java数字\u格式\u异常

这两条线之间的区别是什么,它会删除 我的代码中的运行时错误

如果我使用此选项,则会收到一条错误消息:

int size=Integer.parseInt(br.readline());

但如果我使用了线下,那么它工作得很好

int size=Intger.parseInt(br.readLine().replaceAll("\\s+",""));

错误消息是:

Runtime ErrorException in thread "main" java.lang.NumberFormatException: For input string: "32363 " at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Main.main(File.java:17)


共 (2) 个答案

  1. # 1 楼答案

    在第一个版本中,解析为包含空格的字符串。在错误消息中提到了一条:"32363 "。当您调用br.readLine().replaceAll("\s+","")时,所有的空白都被删除(准确地说,替换为空字符串),并且您已经为解析准备好了一个字符串

    \s是一个用于空格字符的正则表达式字符类,+表示“重复一次或多次”

  2. # 2 楼答案

    根据^{} docs

    Parses the string argument as a signed decimal integer. 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. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

    因此,尽管.replaceAll("\\s+","")现在对您有效,但它并不是所有场景的100%傻瓜式解决方案