java.lang.NumberFormatException:对于输入字符串:“1”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36215779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:05:59  来源:igfitidea点击:

java.lang.NumberFormatException: For input string: "1"

javanumberformatexception

提问by eyeballs

"out.txt" content is

“out.txt”内容是

1

1

My JAVA code is like this.

我的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();

and debugger says,

调试器说,

java.lang.NumberFormatException: For input string: "?1"

java.lang.NumberFormatException:对于输入字符串:“?1”

i need to use 1 from "out.txt". How can i use 1 as Integer? Thank you for your attention :)

我需要使用“out.txt”中的 1。我如何使用 1 作为整数?感谢您的关注 :)

回答by user2004685

You must be having the trailing whitespaces. Use the trim()function as follows:

你一定有尾随空格。使用trim()函数如下:

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 nullor emptyyou can start using the Apache Commons StringUtilsas follows:

此外,如果您想检查 String 是否为null或者empty您可以开始使用 Apache Commons StringUtils,如下所示:

if (StringUtils.isEmpty(line)) break;

回答by Emi Raz

I removed this invisible Unicode character and now parsing to INT works great. I know it's not the case here but maybe can help some other people.

我删除了这个不可见的 Unicode 字符,现在解析为 INT 效果很好。我知道这里不是这样,但也许可以帮助其他人。

text = text.replaceAll("\uFEFF", "");

回答by eyeballs

Oops. Yesterday the following code worked well so i uploaded it as you are seeing. but today, i tried compile one more time without '.toString()' and well, it worked too.So It was my mistake and I'm sorry to bother you guys. (I don't know why it didn't work without '.toString' exactly the day before yesterday.)

哎呀。昨天,以下代码运行良好,所以我如您所见上传了它。但是今天,我尝试在没有 '.toString()' 的情况下再编译一次,结果也很好。所以这是我的错误,很抱歉打扰你们。(我不知道为什么它在前天没有 '.toString' 的情况下不起作用。)



Thank you so much people who cared of my question but i found the answer(i don't know how to find it by myself)

非常感谢关心我问题的人,但我找到了答案(我不知道如何自己找到)

following codes work very well :) Thank you!

以下代码工作得很好:) 谢谢!

    BufferedReader br = new BufferedReader(new FileReader("out.txt"));
    int val=0;

    while(true) {
        String line = br.readLine();
        if (line==null) break;
        val=Integer.parseInt(line.toString());
    }
    br.close();