NullPointerException(初始化String时)

时间:2011-10-29 07:10:47

标签: java string nullpointerexception

以下是引发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时会出现异常?

4 个答案:

答案 0 :(得分:6)

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

whilechrome_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。