java.lang.NumberFormatException:对于输入字符串:“1”(java.lang.NumberFormatException: For input string: “1”)

编程入门 行业动态 更新时间:2024-10-23 21:25:10
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;

更多推荐

本文发布于:2023-07-31 00:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   lang   java   NumberFormatException   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!