简体   繁体   English

Integer.parseInt错误:java.lang.Integer.parseInt(未知源)

[英]Integer.parseInt Error : java.lang.Integer.parseInt(Unknown Source)

I'm working on a Java project to Add each Integer to the one in the next line until there's no lines to read in the file. 我正在一个Java项目中,将每个Integer添加到下一行,直到文件中没有要读取的行。 So to be able to add it I have to use Integer.parseInt(...) to the line then add it. 因此,要添加它,我必须在行中使用Integer.parseInt(...),然后添加它。 PS : the for loop will just skip two lines which contain the header of the file. PS:for循环将只跳过包含文件头的两行。 And all the string are refering to numbers which Integer.parseInt() accepts. 并且所有字符串都引用Integer.parseInt()接受的数字。

Here's the full exception error : 这是完整的异常错误:

Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at prog.Result(prog.java:93)
at prog.main(prog.java:56)

The code resulting in the exception is : 导致异常的代码是:

public static void Result() throws IOException
    {
        FileReader fileReader = new FileReader(dir+"/"+log_file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        int i;
        for (i=0;i<=2;++i)
        {
            bufferedReader.readLine();
        }
        int result =0;
        while (bufferedReader.readLine() != null)
        {
            result += Integer.parseInt(bufferedReader.readLine());

        }
        System.out.println("The Result Is : " + result);

    }

I think this is your problem: 我认为这是您的问题:

    while (bufferedReader.readLine() != null)
    {
        result += Integer.parseInt(bufferedReader.readLine());

    }

You're calling readLine() twice there. 您在那儿两次调用readLine() You should store the initial result in a variable, and the reuse that result in the parseInt() call. 您应该将初始结果存储在一个变量中,并在parseInt()调用中重复使用该结果。

This block is actually reading two lines, not one. 该块实际上正在读取行,而不是一行。

while (bufferedReader.readLine() != null)
{
    result += Integer.parseInt(bufferedReader.readLine());
}

The error occurs when the last line is read in the while condition check, and the inner part of the block will then read null , since there are no more lines to be read. while条件检查中读取最后一行时,将发生错误,并且该块的内部随后将读取为null ,因为没有更多行要读取。

It's idiomatic to write loops like this as: 像这样编写循环是很习惯的:

String line;
while ((line = bufferedReader.readLine()) != null)
{
    result += Integer.parseInt(line);
}

First: you should check data in your file to ensure that all lines are number. 首先:您应该检查文件中的数据以确保所有行都是数字。

Second: you should try catch at the line as below 第二:您应该尝试在以下行抓到

try {
    result += Integer.parseInt(bufferedReader.readLine());
} catch(Exception ex)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM