以下是引发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();
遇到此代码段时,会抛出NullPointerException
。如果我将writer.write(chrome_count_S);
的参数替换为writer.write("chrome_count_S");
I.E.一个String
,我没有任何例外。否则,为什么在初始化字符串chrome_count_S
时会出现异常?
答案 0 :(得分:6)
当while
为readline()
时null
循环停止,并将当前值写入变量chrome_count_S
。
while((chrome_count_S = br.readLine()) != null)
因此chrome_count_S
在循环后和null
命令后为write
。
=== UPDATE ===
删除循环中的chrome_count_S
行,并在写入过程中从chrome_count_I
获取值:
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));
答案 1 :(得分:2)
while
为chrome_count_S
之前,您的null
循环不存在。因此,对writer.write()
的调用当然会抛出NullPointerException
。
答案 2 :(得分:1)
可能是因为在writer.write
之前,你有了while循环
while((chrome_count_S = br.readLine()) != null)
仅在br.readline()
将NULL
放入chrome_count_S
答案 3 :(得分:0)
即使你初始化它,br.readLine()在某些时候为chroe_count_S指定了null。