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();
}
}
错误是:
“线程“主”中的异常” java.lang.NullPointerException
在imdb.url.main(url.java:25)“
请向我解释如何删除它。我已经用google搜索了很多关于使用分割函数和空指针异常的信息,但是只是不明白我在做什么错。
最佳答案
当while循环退出时,inputLine
为null,因此调用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);
}
这有预期的效果吗?