【问题标题】:Exception in thread "main" java.lang.NullPointerException [maxMind]线程“main”中的异常 java.lang.NullPointerException [maxMind]
【发布时间】:2013-11-07 19:40:38
【问题描述】:
   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);
            }
    }

我使用我的主类读取逐行保存IP地址的txt,并希望将它们保存到对象中并保存到数组中。
我测试了我的代码,我得到了运行时错误。 140.118.175.208 经度 121.524994 纬度 25.0392 线程“主”java.lang.NullPointerException 中的异常 我添加 S[1] System.out.println("longtitude" + S[1].getLongtitude()); 它向我展示了同样的问题并且不打印 S[1] 值 我不知道发生了什么?我想我已经分配了数组 obj?谢谢!

【问题讨论】:

  • 你能检查记录是否为空吗?
  • NullPointerException 发生在哪一行?堆栈跟踪将为您的课程提供一个行号。
  • 我的回答解决了您的问题吗?
  • 是的,将其移出循环。谢谢。

标签: java nullpointerexception maxmind


【解决方案1】:

问题出在一行:

Site S[]= new Site[100];  

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

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

【讨论】:

  • 天哪!非常感谢你。我太三心二意了。它有效。
猜你喜欢
  • 2013-11-21
  • 1970-01-01
  • 2012-12-09
  • 2023-03-10
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
相关资源
最近更新 更多