使用 readLine() 继续获取此异常

Keep Getting this Exception With readLine()

所以我正在尝试使用 BufferedReader 编写一个循环,该循环读取下一行,将该行转换为双精度数,然后将其添加到总和中。这是继续到文件末尾。

出于某种原因,我一直收到此错误,

Exception in thread "main" java.lang.NullPointerException
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1017)
    at java.lang.Double.parseDouble(Double.java:540)

这是我的代码:

while(bReader.readLine() != null)
      {
         line = bReader.readLine();
         double num = Double.parseDouble(line);
         sum = sum + num;
         count++;
      }

您在 while 循环中读取了一个新行,即 returns null:

while(bReader.readLine() != null)
      {
         line = bReader.readLine(); // read a second line
         double num = Double.parseDouble(line);
         sum = sum + num;
         count++;
      }

更改为:

while((line = bReader.readLine()) != null)
      {
         double num = Double.parseDouble(line);
         sum = sum + num;
         count++;
      }