-2

当 Java 应用程序或 Java 小程序编码错误时,会发生 java.lang.NullPointerException。通常,Java 程序(以及程序员)试图访问不存在的 Java 对象的引用或句柄

我在转圈阅读。我已经制作了两个最小文件 - Two.java 将编译。

 public class Two {
   public static int width;
   public static int height;

   public static void main(String[] args) {
     int width = 320;
     int height = 100;  
     System.out.println(width + "," + height);
   }
 }

Eclipse 中的 One.java 会将字符串 intwo 打印到控制台。我的问题是它是否会打印,为什么它是空的?我正在尝试将字符串转换为 int,以便我可以用它进行数学运算。在现实生活中,到达的数字远不止两个。

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class One {
  public static int width;
  public static int height;

  public static void main(String[] args) throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec("java -jar Two.jar");
    BufferedReader is;
    String intwo;
    is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((intwo = is.readLine()) != null)
      System.out.println(intwo); // Prints to console

    String[] items = (intwo).split(","); //java.langNullPointerException
    int[] results = new int[items.length];

    for (int i = 0; i < items.length; i++) {
      results[i] = Integer.parseInt(items[i]);
    }
    System.out.println(results[1]);
  }
}
4

5 回答 5

2
while ((intwo = is.readLine()) != null)
  System.out.println(intwo); // Prints to console

//Here intwo is guaranteed to be null!!!!
String[] items = (intwo).split(",");

顺便说一句,编写if/while不带花括号的语句是一种不好的做法。你真的应该避免它。

于 2013-08-06T13:04:49.417 回答
1
while ((intwo = is.readLine()) != null)
    System.out.println(intwo); // Prints to console
String[] items = (intwo).split(","); //java.langNullPointerException

当然你会得到 NullPointerException。您基本上迭代直到 intwo 为空(因此您确保intwo 为空),然后您在该空引用上调用一个方法。

于 2013-08-06T13:08:33.393 回答
1

这是你的while条款:

while ((intwo = is.readLine()) != null)
  System.out.println(intwo); // Prints to console

它在什么时候存在intwonull对吧?所以很明显,下一行将intwonull 并且将导致NullPointerException

String[] items = (intwo).split(","); //java.langNullPointerException
于 2013-08-06T13:05:33.780 回答
1

查看您的代码:

while ((intwo = is.readLine()) != null)

你什么时候退出while循环?intwo什么时候null

因此,当您退出循环时,您所做null.split(",");的当然会导致 NPE。

在循环周围加上括号while,你应该没问题。

于 2013-08-06T13:05:50.300 回答
0

这个:

 while ((intwo = is.readLine()) != null)
 System.out.println(intwo); // Prints to console
 String[] items = (intwo).split(","); 

与此相同:

while ((intwo = is.readLine()) != null){
    System.out.println(intwo); // Prints to console
}

String[] items = (intwo).split(","); 

很明显为什么你会得到 NullPointerException

于 2013-08-06T13:03:48.413 回答