Reputation: 23206
Following is a snippet that throws java.lang.NullPointerException
.
else if(jRadioButton2.isSelected()) {
// chrome selected
String chrome_count_S="0";
int chrome_count_I=0;
FileWriter writer = new FileWriter("D:\\UnderTest\\MyFirstPoll\\build\\classes\\poll_count\\Chrome.txt");
FileReader reader = new FileReader("D:\\UnderTest\\MyFirstPoll\\build\\classes\\poll_count\\Chrome.txt");
BufferedReader br = new BufferedReader(reader);
while((chrome_count_S = br.readLine()) != null) {
chrome_count_I = Integer.parseInt(chrome_count_S);
chrome_count_I++;
chrome_count_S = Integer.toString(chrome_count_I);
}
writer.write(chrome_count_S);
writer.close();
When this snippet is encountered NullPointerException
is thrown. If I replace the argument of writer.write(chrome_count_S);
to writer.write("chrome_count_S");
I.E. a String
, I don't get any exception. Otherwise why do I get the exception when I have initialized the string chrome_count_S
?
Upvotes: 0
Views: 459
Reputation: 16115
The while
loop stops when the readline()
is null
and writes the current value to the variable chrome_count_S
.
while((chrome_count_S = br.readLine()) != null)
So chrome_count_S
is be null
after the loop and at the the write
command.
=== UPDATE ===
Remove the chrome_count_S
row in the loop and take the value from the chrome_count_I
during writing:
while((chrome_count_S = br.readLine()) != null) {
chrome_count_I = Integer.parseInt(chrome_count_S);
chrome_count_I++;
}
writer.write(Integer.toString(chrome_count_I));
Upvotes: 6
Reputation: 2257
Even though you initialized it, at some point br.readLine() assigns null to chroe_count_S.
Upvotes: 0
Reputation: 6052
probably because before the writer.write
, you have the while loop
while((chrome_count_S = br.readLine()) != null)
which ends only when br.readline()
puts a NULL
in the chrome_count_S
Upvotes: 1
Reputation: 7336
Your while
loop doesn't exist until chrome_count_S
is null
. So of course the call to writer.write()
will throw a NullPointerException
.
Upvotes: 2