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

时间:2016-03-25 07:28:54

标签: java numberformatexception

“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作为整数? 感谢您的关注:))

3 个答案:

答案 0 :(得分:4)

您必须拥有尾随空格。使用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;

答案 1 :(得分:0)

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

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

答案 2 :(得分:-1)

糟糕。昨天以下代码运作良好,所以我上传了你看到的。但今天,我尝试再编译一次没有'.toString()'而且,它也有效。所以这是我的错误,我很抱歉打扰你们。 (我不知道为什么在前一天没有'.toString'就行不通。)

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

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

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