问题在线:
Site S[]= new Site[100];
对于每次迭代,您都会创建一个新的数组,因此最后它只充满了无效指针。当您尝试访问s [0]时,它将在第二次迭代中为您提供空指针。
这就是为什么它首次打印的原因,但是第二次获得无效指针。第一次S [0]具有一个值,第二次没有。
题
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);
}
}
我使用我的主类读取txt,该TXT通过行保存IP地址,并希望将它们保存到对象中并保存到数组中。
我测试了我的代码,并遇到了运行时间错误。 140.118.175.208长度121.524994纬度25.0392线程中的异常“ main” java.lang.lang.nullpointerexception,我添加s [1] system.out.out.println(“ longtitude” + s [ + s [1] .getLongtitude().getLongtitude());它向我展示了同样的问题,并且不打印s [1]值我不知道发生了什么?我想我已经分配了阵列OBJ?谢谢!
解决方案
问题在线:
Site S[]= new Site[100];
对于每次迭代,您都会创建一个新的数组,因此最后它只充满了无效指针。当您尝试访问s [0]时,它将在第二次迭代中为您提供空指针。
这就是为什么它首次打印的原因,但是第二次获得无效指针。第一次S [0]具有一个值,第二次没有。