java.lang.NumberFormatException:对于输入字符串:“1”(java.lang.NumberFormatException: For input string: “1”)
“out.txt”的内容是
1
我的JAVA代码是这样的。
int val=0; BufferedReader br = new BufferedReader(new FileReader("out.txt")); while(true) { String line = br.readLine(); if (line==null) break; val=Integer.parseInt(line); } br.close();和调试器说,
java.lang.NumberFormatException:对于输入字符串:“1”
我需要使用“out.txt”中的1。 我如何使用1作为整数? 感谢您的关注 :)
"out.txt" content is
1
My JAVA code is like this.
int val=0; BufferedReader br = new BufferedReader(new FileReader("out.txt")); while(true) { String line = br.readLine(); if (line==null) break; val=Integer.parseInt(line); } br.close();and debugger says,
java.lang.NumberFormatException: For input string: "1"
i need to use 1 from "out.txt". How can i use 1 as Integer? Thank you for your attention :)
最满意答案
你必须有尾随的空格。 使用trim()函数如下:
val = Integer.parseInt(line.trim());这是代码片段:
int val = 0; BufferedReader br = new BufferedReader(new FileReader("out.txt")); String line = null; while(true) { line = br.readLine(); if (line == null) break; val = Integer.parseInt(line.trim()); } br.close();此外,如果要检查String是null还是empty您可以开始使用Apache Commons StringUtils ,如下所示:
if (StringUtils.isEmpty(line)) break;You must be having the trailing whitespaces. Use the trim() function as follows:
val = Integer.parseInt(line.trim());Here is the code snippet:
int val = 0; BufferedReader br = new BufferedReader(new FileReader("out.txt")); String line = null; while(true) { line = br.readLine(); if (line == null) break; val = Integer.parseInt(line.trim()); } br.close();Also, if you want to check whether String is null or empty you can start using the Apache Commons StringUtils as follows:
if (StringUtils.isEmpty(line)) break;更多推荐
发布评论