硬编码2d数组到构造函数中

时间:2015-01-27 23:27:02

标签: java

我目前正在尝试将预设值硬编码到构造函数中,它给了我一个“非法启动消息”。如果它不允许那么好我想我会试着找到一个解决方法。我正在处理的程序使用matrix1的特定值,使其余的程序工作。我是一个初学者,所以我可能只是做错了。我查看了Java API,发现什么都没说我不能做我想做的事。我有一个AssignmentOne类,其中编码的方法和构造函数以及AssignmentOneTest来测试代码。我真的想为此使用两个类。  以下是我的代码:

public class AssignmentOne {
private double[][] matrix1;
private double[][] matrix3;

public AssignmentOne(){
  matrix3 = new double[3][3];
  matrix1 = {{0.9,0.05,0.05},
             {0.05,0.9,0.05},
             {0.05,0.05,0.9}};

}//Constructor END

3 个答案:

答案 0 :(得分:1)

您只能对声明它的数组进行硬编码,而不是稍后在代码中编码。所以这没关系:

public class AssignmentOne {
    double[][] matrix1 = {{0.9,0.05,0.05},
             {0.05,0.9,0.05},
             {0.05,0.05,0.9}};

    public AssignmentOne(){

        // now you are free to use matrix1 here if need be

    }

但这不是:

public class AssignmentOne {
    double[][] matrix1;

    public AssignmentOne(){
      matrix1 = {{0.9,0.05,0.05},
                 {0.05,0.9,0.05},
                 {0.05,0.05,0.9}};        
    }

另一个可行的解决方案是允许构造函数接受数组参数,并传入在其他位置初始化的数组,例如在main方法中:

public class AssignmentOne {
    double[][] matrix1;

    public AssignmentOne(double[][] matrix1){
       this.matrix1 = matrix1; 
    }

然后在其他地方:

public static void main(String[] args) {
    double[][] arr = {{0.9,0.05,0.05},
             {0.05,0.9,0.05},
             {0.05,0.05,0.9}};

    AssignmentOne assignmentOne = new AssignmentOne(arr);
}

答案 1 :(得分:0)

您应该使用new double[][]new double[]我想:

matrix1 = new double[][] {new double[]{0.9,0.05,0.05},
                          new double[]{0.05,0.9,0.05},
                          new double[]{0.05,0.05,0.9}};

也许你忘了关闭第一个}。这是因为我们正在讨论由方法改变的变量(是构造函数是一种方法,在创建对象后立即执行的方法),因此该值不能是常量。您需要使用new上分配它。

ideone demo(姓名不同)

答案 2 :(得分:0)

您无法在构造函数中使用常量初始化数组。但是,您可以在声明变量

时直接初始化它
public class AssignmentOne {
    private double[][] matrix1 = {{0.90, 0.05, 0.05},
                                  {0.05, 0.90, 0.05},
                                  {0.05, 0.05, 0.90}};
    private double[][] matrix3;

    public AssignmentOne(){
        matrix3 = new double[3][3];
    }
}

或者,您可以在构造函数

中动态创建它
public AssignmentOne(){
    matrix3 = new double[3][3];
    matrix1 = new double[][] {new double[]{0.90, 0.05, 0.05},
                              new double[]{0.05, 0.90, 0.05},
                              new double[]{0.05, 0.05, 0.90}};
}