java.lang.NumberFormatException: For input string: “23 ” [duplicate]

倖福魔咒の 提交于 2019-12-05 22:11:50

Your String has a trailing white space.

int Q = Integer.parseInt(tempStr.trim());

Use Scanner.nextInt() and avoid to parse the String.

Also it's useful the method Scanner.hasNextInt().

Take a look at the closing doublequote " on the exception - it is positioned on the next line, meaning that the input string has '\n' or '\r' at the end.

You can fix this by calling trim() before passing the string to the parsing method, but you would be better off having next() strip the end-of-line character for you by using system-specific line separator, like this:

cin.useDelimiter(System.lineSeparator());

or by calling hasNextInt/nextInt to let the scanner do the conversion.

Input String if parsed as integer then its must be valid integer value no decimal, space, line-break or any other character. So make sure The Input String throw in exception is valid integer or not if contain any other character, decimal, space/line-break then try to remove that.

It's my standard answer to such questions:

Exception in thread "main" java.lang.NumberFormatException: For input string: "23
"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Chef.RegexTestHarness.main(RegexTestHarness.java:24)

means:

There was an error. We try to give you as much information as possible
It was an Exception in main thread. It's called NumberFormatException and has occurred for input "23\n".
which was invoked from method main in file RegexTestHarness.java in line 24.

In other words, you tried to parse "23\n" to an int what Java can't do with method Integer.parseInt. Java has provided beautiful stacktrace which tells you exactly what the problem is. The tool you're looking for is debugger and using breakpoints will allow you to inspect the state of you application at the chosen moment.

As mentioned before, it's safe to use tempStr.trimm() before parsing to the int.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!