【问题标题】:Global Array in a class initialized size based on a pass parameter issue基于传递参数问题的类初始化大小中的全局数组
【发布时间】:2018-02-05 19:03:58
【问题描述】:

我有一个名为matrixDec 的类(参见下面的代码),我想做的是将2 个变量传递给构造函数,然后使用这些变量初始化一个维度为matrix[row][col] 的数组。我遇到的问题是运行程序时出现越界错误。我怀疑这是因为当我调用 matrixDec 类时,整数 row 和 col (全局版本)都在构造函数被调用之前用 null0 初始化,所以数组开始 0,0null, null .

所以现在,我希望能够在整个班级中对数组进行操作,并且我希望它的维度为 row, col

private int row;
private int col;    
private String matrix[][] = new String[row][col];

//constructor for calss matricDec
public void matrixIni(int row, int col){
    this.row = row;
    this.col = col;

    //matrix[1][1] = "test";
    //System.out.println(matrix[1][1]);
}

【问题讨论】:

  • 请注意public void matrixIni(int row, int col) 不是构造函数,它是一个类方法。在 Java 中,构造函数没有返回类型。
  • 哦,我现在记起来了。已经好几年了,谢谢你指出这一点。

标签: java arrays class


【解决方案1】:

您需要在构造函数中初始化数组,而不是在声明它时。像这样:

public class matrixIni {
    private int row;
    private int col;    
    private String matrix[][];

    //constructor for calss matricDec
    public matrixIni(int row, int col){
        this.row = row;
        this.col = col;
        matrix[][] = new String[row][col]

        //matrix[1][1] = "test";
         //System.out.println(matrix[1][1]);
    }
}

【讨论】:

    【解决方案2】:

    你不能在那里初始化matrix,因为rowcol还没有赋值,所以它们是默认的0

    在构造函数中也初始化matrix

    this.row = row;
    this.col = col;
    matrix = new String[row][col];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多