Question

   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!

Was it helpful?

Solution

The problem is in the line:

Site S[]= new Site[100];  

For each iteration you create a new array, so at the end it is only filled with null pointers. When you try to access the s[0] it is going to give you null pointer on second iteration.

That is why it first prints, but the second time you get a null pointer. First time the s[0] has a value, the second time it does not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top