由NullPointerException引起的错误

时间:2014-07-19 16:54:59

标签: java nullpointerexception jsoup

班级考试

package test;
import java.io.IOException;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.Scanner;
public class test {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        String  url, artistIn, artist, base;
        SongUrl[] obj = new SongUrl[100];
        base = "http://lyrics.wikia.com/";
        int count = 0;
        System.out.println("Enter an artist");
        artistIn = in.nextLine();
        artist = artistIn.replace(' ', '_');
        url = "http://lyrics.wikia.com/api.php?func=getSong&artist=" + artist + "&fmt=html";
        Document doc = Jsoup.connect(url).get();
        Elements a = doc.select("a[href]");
        for(Element alink : a){
            obj[count] = new SongUrl();
            obj[count].urlSong = alink.toString();
            count++;
            obj[count].serialNo = count;      //Faced NPE on this line
            System.out.println(count + " " + alink.html());
        }
    }
}

Class SongUrl

public class SongUrl {
    int serialNo;
    String urlSong;
}

我在线上遇到了NullPointerException obj[count].serialNo = count; 。令人惊讶的是,如果要发生NPE,它应该发生在它之前的这条线obj[count].urlSong = alink.toString();上。我对于出了什么问题一无所知。

2 个答案:

答案 0 :(得分:1)

你增加了count,现在它指向数组中null

的下一个项目
  obj[count].urlSong = alink.toString();
  count++;                      // this is causing the issue
  obj[count].serialNo = count;  // obj[count] is null  

在for循环结束时增加count


我建议您在声明下方初始化以避免此类NullPointerException

 SongUrl[] obj = new SongUrl[100];
 for(int i=0;i<obj.length;i++){
        obj[i] = new SongUrl();
 }

最好使用ArrayList

保留会员private并使用getter&amp;二传手术方法。详细了解Encapsulation

public class SongUrl {
    private int serialNo;
    private String urlSong;
    // getter & setter
}

答案 1 :(得分:1)

在设置count之前增加serialNo - 由于此数组的索引尚未初始化,因此您获得NullPointerException。为避免这种情况,您应该最后增加count

obj[count] = new SongUrl();
obj[count].urlSong = alink.toString();
obj[count].serialNo = count + 1; // Note the +1 - count is incremented afterwards
count++;