0

我有一个带有配置文件的参数化构造函数的前馈类:

public Feedforward(String cfg) throws Exception {

    super(cfg);
    String tempstr = "";
    int currNeuronNum = 0;
    int currEdgeNum = 0;
    int currLayerID = 0;
    int count = 0;

    if (!(type).equals("feedforward")) {
       throw new Exception("cfgError: specify proper type")
    //more code
    }

其中 super(cfg) 调用 Network 类的构造函数,我在其中处理文件解析和通用字段的存储:

protected Network(String cfgPath) throws IOException, Exception {

      String type;
      String activationFunction;
      double bias;
      /*file reading stuff; checked with print statements and during 
        the creation of a Feedforward class, successfully prints 
        "feedforward" after reading type from file
      */       
}

当我运行测试时,它会抛出 NullPointerException。前馈中的类型变量未分配存储在 cfgPath/cfg 文件中的值,因此出现异常。为什么构造函数链接不这样做,我该如何做不同的事情?

4

1 回答 1

0

因为 type 是方法的局部变量(在这种情况下是构造函数),虽然 Network 是一个超类,但我们不能访问它之外的任何方法的局部变量。

你可以让 String type=""; 作为外部构造函数的变量,然后只需在网络构造函数中分配值。

你可以在前馈类中使用它。

public class Network {
     String type="";
    protected Network(String cfgPath) throws IOException, Exception  {

         type=cfgPath;
          String activationFunction=cfgPath;
          double bias;
          /*file reading stuff; checked with print statements and during 
            the creation of a Feedforward class, successfully prints 
            "feedforward" after reading type from file
          */       
    }
}
于 2019-03-27T03:33:14.330 回答