gpt4 book ai didi

java - 由于 NullPointerException 导致的错误

转载 作者:行者123 更新时间:2023-12-02 05:37:27 25 4
gpt4 key购买 nike

类测试

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());
}
}
}

SongUrl 类

public class SongUrl {
int serialNo;
String urlSong;
}

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

最佳答案

您已经增加了计数,现在它指向数组中的下一项null

  obj[count].urlSong = alink.toString();
count++; // this is causing the issue
obj[count].serialNo = count; // obj[count] is null

在 for 循环末尾增加计数

<小时/>

我建议您在声明下方进行初始化,以避免出现此类 NullPointerException

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

更好用ArrayList

保持成员私有(private)并使用getter和setter方法。了解更多关于 Encapsulation

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

关于java - 由于 NullPointerException 导致的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24842765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com