我正在编写一个基本程序来获取许多高中的学校网站,但由于某种原因,程序随机开始给我NullPointerExceptions。通过随机我的意思是,我测试了一组代码,我知道在这个代码开始发生之前已经100%工作,它不再有效。它也是随机的,有时候程序会返回5所学校,有时候它会在第一所学校得到NullPointerException。我目前所拥有的内容如下所示,NullPointer异常发生在System.out.println()和pw.write()。我觉得这意味着查询没有返回任何内容,但就在不久之前。
public static void main(String[] args) throws IOException {
File infile = new File("inputschools.txt");
Scanner in = new Scanner(infile);
PrintWriter pw = new PrintWriter("outputschools.txt");
while(in.hasNextLine()){
String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=1&q=";
String query = in.nextLine() + " high school ohio";
String charset = "UTF-8";
URL url = new URL(address + URLEncoder.encode(query, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
System.out.println("URL: " + results.getResponseData().getResults().get(0).getUrl() + "\n");
pw.write(results.getResponseData().getResults().get(0).getUrl() + ",");
}
}
}
编辑:这是请求的堆栈跟踪,但我认为它不会非常有用。
Exception in thread "main" java.lang.NullPointerException
at GoogleSearch.main(GoogleSearch.java:32)
第32行是println()段。
EDIT2:
这是实际GoogleResults对象的代码。我介入了该程序,由于某种原因,GoogleResult在第二次迭代中为空。谁能看到/想到为什么会这样?
class GoogleResults{
private ResponseData responseData;
public ResponseData getResponseData() { return responseData; }
public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
public String toString() { return "ResponseData[" + responseData + "]"; }
static class ResponseData {
private List<Result> results;
public List<Result> getResults() { return results; }
public void setResults(List<Result> results) { this.results = results; }
public String toString() { return "Results[" + results + "]"; }
}
static class Result {
private String url;
private String title;
public String getUrl() { return url; }
public String getTitle() { return title; }
public void setUrl(String url) { this.url = url; }
public void setTitle(String title) { this.title = title; }
public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
}
}