استثناء في الموضوع "الرئيسي" java.lang.nullpointerxception [maxmind

StackOverflow https://stackoverflow.com/questions/19845112

سؤال

   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 التي تحفظ سطر عنوان IP سطرًا وتريد حفظها في كائن وحفظها في صفيف.
أختبر الكود الخاص بي ، وحصلت على خطأ في وقت التشغيل. 140.118. إنها تُظهر لي نفس المشكلة ولا تطبع القيمة [1] لا أعرف ماذا حدث؟ أعتقد أنني قمت بتعيين Array OBJ؟ شكرًا لك!

هل كانت مفيدة؟

المحلول

المشكلة في الخط:

Site S[]= new Site[100];  

لكل تكرار ، تقوم بإنشاء مجموعة جديدة ، لذلك في النهاية تمتلئ فقط بمؤشرات فارغة. عندما تحاول الوصول إلى S [0] ، فسوف يمنحك مؤشرًا فارغًا في التكرار الثاني.

هذا هو السبب في أنه يطبع أولاً ، ولكن في المرة الثانية التي تحصل فيها على مؤشر فارغ. لأول مرة S [0] لها قيمة ، في المرة الثانية التي لا.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top