0
public class url {


 public static void main(String[] args) throws Exception {

    URL imdb = new URL("http://www.omdbapi.com/?t=The%20incredible%20Hulk");

    URLConnection yc = imdb.openConnection();

    BufferedReader in = new BufferedReader(new InputStreamReader(
                                yc.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);

    String[] strarr = inputLine.split(",");


    System.out.println("splits.size: " + strarr.length);

    in.close();
}
}

错误是:“imdb.url.main(url.java:25) 处的线程“main”java.lang.NullPointerException 中的异常”

请向我解释如何删除它。我在使用拆分函数和空指针异常方面搜索了很多,但就是不明白我做错了什么。

4

5 回答 5

5

如果从in.readLine()in 返回 null:

 while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);

然后循环将退出并inputLine保持为空。

从逻辑上讲,循环结束时inputLine始终为空,因此不可避免的异常!

于 2013-03-30T21:19:39.757 回答
5

当您的 while 循环退出时,inputLine为空,因此调用inputLine.split()将始终产生一个NullPointerException. 我相信您想要做的是将大括号括在System.out.println()调用及其之间的所有内容中,以便它们都包含在循环迭代中:

 while ((inputLine = in.readLine()) != null)
 {
    System.out.println(inputLine);

    String[] strarr = inputLine.split(",");

    System.out.println("splits.size: " + strarr.length);
}

这有预期的效果吗?

于 2013-03-30T21:20:24.760 回答
3

您的 while 循环中缺少括号。inputLine当您尝试它时导致为空split()。尝试

 while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);

    String[] strarr = inputLine.split(",");

    System.out.println("splits.size: " + strarr.length);
}
于 2013-03-30T21:20:30.953 回答
2

到达时String[] strarr = inputLine.split(",");,您已经阅读了整个响应 - 但此时inputLinenull到达,因此您无法拆分它。

How to fix this depends on what you are trying to do. If you want to split the whole document, try collecting all the data in one big string:

String inputLine;
String allData = "";

while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
    allData += inputLine+"\n";
}

String[] strarr = allData.split(",");

(This code is a bit inefficient, but it should work.)

However, your URL points to a JSON document, so you might want to use a JSON parser instead of doing this. It will be more reliable and probably also easier than trying to parse JSON manually. For information on JSON and JSON libraries for various languages, see http://json.org .

于 2013-03-30T21:22:16.603 回答
1

这是因为inputline上次在While循环中读取时,没有任何内容被读取inputLine。因此,while当您尝试执行循环后spliinputline它会给出NullPointerExcpetion.

while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
System.out.println(inputLine);//InputLine is null here.
String[] strarr = inputLine.split(",");//throwing NPE

解决方法是使用 StringBuilder,如下所示:

StringBuilder sbuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) 
            sbuilder.append(inputLine);
String[] strarr = (sbuilder.toString()).split(",");
于 2013-03-30T21:18:33.527 回答