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

I use my main class to read txt that save ip address line by line and want to save them into object and save into array.
I test my code ,and i got run time error. 140.118.175.208 longtitude 121.524994 latitude 25.0392 Exception in thread "main" java.lang.NullPointerException and i add S[1] System.out.println("longtitude " + S[1].getLongtitude()); It show me the same problem and don't print S[1] value I don't know what happened? I think i had assigned array obj?Thank you!

4

1 回答 1

3

问题在于:

Site S[]= new Site[100];  

对于每次迭代,您都会创建一个新数组,因此最后只填充空指针。当您尝试访问 s[0] 时,它将在第二次迭代时为您提供空指针。

这就是为什么它第一次打印,但第二次得到一个空指针。第一次 s[0] 有一个值,第二次没有。

于 2013-11-07T19:42:52.573 回答