“线程中的异常”;“主要”;java.lang.NullPointerException[maxMind]
我使用我的主类读取逐行保存ip地址的txt,并希望将它们保存到对象中并保存到数组中。“线程中的异常”;“主要”;java.lang.NullPointerException[maxMind],java,nullpointerexception,maxmind,Java,Nullpointerexception,Maxmind,我使用我的主类读取逐行保存ip地址的txt,并希望将它们保存到对象中并保存到数组中。 我测试了我的代码,得到了运行时错误。 140.118.175.208 长121.524994 纬度25.0392 线程“main”java.lang.NullPointerException中出现异常 我添加了S[1]System.out.println(“longtude”+S[1].getlongtude()); 它显示了相同的问题,并且不打印S[1]值 我不知道发生了什么事?我想我已经分配了阵列obj?谢
我测试了我的代码,得到了运行时错误。 140.118.175.208 长121.524994 纬度25.0392 线程“main”java.lang.NullPointerException中出现异常 我添加了S[1]System.out.println(“longtude”+S[1].getlongtude()); 它显示了相同的问题,并且不打印S[1]值
我不知道发生了什么事?我想我已经分配了阵列obj?谢谢 问题在于:
public class CountryLookupTest {
public static void main(String[] args) {
String location1=null;
try {
int number=0;
LookupService citylookup = newLookupService("D://GeoLiteCity.dat",
LookupService.GEOIP_MEMORY_CACHE );
FileReader fr =new FileReader("d:\\IP.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while( (line = br.readLine()) != null ){
location1=line;
System.out.println(location1);
Location record = citylookup.getLocation(location1);
Site S[]= new Site[100];
S[number]= new Site(record.longitude,record.latitude);
number++;
System.out.println("longtitude " + S[0].getLongtitude());
System.out.println("latitude " + S[0].getLatitude());
}
public class Site {
private float longitude;
private float latitude;
public Site(float a, float b){
setLongitude(a);
setLatitude(b);
}
}
对于每个迭代,您都会创建一个新数组,因此在最后它只会被空指针填充。当您尝试访问s[0]时,它将在第二次迭代时为您提供空指针
这就是为什么它第一次打印,但第二次得到空指针。第一次s[0]有值时,第二次没有 您能检查记录是否为空吗?NullPointerException发生在哪一行?堆栈跟踪将为您的类提供行号。我的答案是否解决了您的问题?是的,将其移出循环。谢谢,天哪!非常感谢你。我太心不在焉了。它起作用了。
Site S[]= new Site[100];