Reputation: 19
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. So to be able to add it I have to use Integer.parseInt(...) to the line then add it. P.S : the for loop will just skip two lines which contain the header of the file. And all the string are refering to numbers which Integer.parseInt() accepts.
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);
}
Upvotes: 0
Views: 17811
Reputation: 926
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)
Upvotes: 0
Reputation: 77044
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.
It's idiomatic to write loops like this as:
String line;
while ((line = bufferedReader.readLine()) != null)
{
result += Integer.parseInt(line);
}
Upvotes: 5
Reputation: 33019
I think this is your problem:
while (bufferedReader.readLine() != null)
{
result += Integer.parseInt(bufferedReader.readLine());
}
You're calling readLine()
twice there. You should store the initial result in a variable, and the reuse that result in the parseInt()
call.
Upvotes: 5