2013-12-09 17 views
2

在交换机内部,我创建了一个Hive类的实例,它在创建对象之后返回到我的交换机,然后在出现错误之前命中中断在交换机中构造一个对象时创建的java.lang.ExceptionInInitializerError

Exception in thread "main" java.lang.ExceptionInInitializerError 
    Caused by: java.lang.NullPointerException 
at Garden.fileReader(Garden.java:141) 
at Garden.<init>(Garden.java:28) 
at Garden.<clinit>(Garden.java:10)' 

误差通过switch语句然后运行到一个单独的类来构造对象和返回时,打破错误弹出

public class Garden { 
    public static final Garden GARDEN = new Garden(); //line 10------------ 
    public static void main(String[] args) { 


     int mainI = 0; 
     while (mainI != 100) { 
      try { 
       Thread.sleep(500); 
      } catch (InterruptedException e) { 
      } 
      GARDEN.anotherDay(); 
      mainI++; 
     } 
    } 
    static HashMap<String, Hive> HiveMap = new HashMap<String, Hive>(); 

    private Garden() { 

     fileReader(); //line 28 -------------------------- 
     System.out.println("fileReader worked"); 
    } 



    protected void fileReader() { // asks for file name for config file 

     //removed try catch code that uses Scanner to get input from console 
     // to select a file that is set to configFile 

     Scanner configScanner = new Scanner(configFile); 
     int k = 0; 

     while (configScanner.hasNextLine() == true) { 
      String inputLine = configScanner.nextLine(); 
      //removed long if statment to set k 

      switch (k) { 
      case 1: 
       intFinder(k, inputLine); 
       Hive hive = new Hive(honeyInput, pollenInput, royalJellyInput); 
       HiveMap.put("hive" + hiveName, hive); line 141------------- 
       break; // it gets to this break then throws the error 

       // removed code 
      default: 
       break; 
      } 
     } 
     cmdReader.close(); 
     configScanner.close(); 
    } 

用于蜂房的构造是

012之后发生
protected Hive(int honeyStart, int royalJellyStart, int pollenStart) 
{ 
    bees = new ArrayList<Bee>(); 
    this.setHoney(honeyStart); 
    this.setRoyalJelly(royalJellyStart); 
    this.setPollen(pollenStart); 
} 

对不起张贴这么多的代码,但我唯一的想法发生了什么事情错了configScanner丢失数据时,代码另一类是跑了,这是不是这样我不知道发生了什么事情不对任何帮助将是非常感谢

回答

2

这是因为在Garden GARDEN的初始化器运行时,HiveMap尚未初始化。此举初始化HiveMap提前Garden GARDEN一行行来解决这个问题:

static HashMap<String, Hive> HiveMap = new HashMap<String, Hive>(); 
public static final Garden GARDEN = new Garden(); 

之所以这样可以解决的问题是,静态初始化在文本顺序运行。该Garden()构造假定HiveMap就是非空的,因为它试图把数据吧:

HiveMap.put("hive" + hiveName, hive); 
+0

谢谢你这么简单一直试图弄清楚是什么导致它与大约一个小时玩遍各地 – user1642671

1

一成不变的东西,以便进行评估。在第10行中,您尝试创建new Garden(),它尝试访问静态成员HiveMap,但尚未初始化。只需将new Garden()转换为main方法即可。

+0

当试图从花园外访问它时,将新的Garden()转移到主要的原因错误中 – user1642671

相关问题