用Java打印二维构造函数

时间:2018-03-15 02:23:39

标签: java arrays constructor 2d

我需要从main方法打印构造函数中的2d数组的值。每次调用 mainSc 数组时,我都会为2d数组中的每个值获得 null 的值。为什么这样,我如何修复数组以从构造函数调用值?

public class Main {
    public static void main(String[] args) {
        String[][] mainSc = new String[5][5];

        System.out.println(Arrays.deepToString(mainSc));
    }
}

import java.util.Arrays;

public class Schedule {
    private int numDays;
    private int numClasses;
    private String[][] Cal;

    public Schedule(String[][] array) {
        this.numDays = 5;
        this.numClasses = 4;
        this.Cal = array;
    }
    public String[][] Array() {
        for (int r = 0; r < numDays; r++){
            for (int j = 0; j <= numClasses; j++){
                this.Cal[0][0] = "Monday";
                this.Cal[1][0] = "Tuesday";
                this.Cal[2][0] = "Wednesday";
                this.Cal[3][0] = "Thursday";
                this.Cal[4][0] = "Friday";  
            }
        }
      return this.Cal;
    }
    public void printSchedule() {
        for (int r = 0; r <= numDays; r++){
            for (int j = 0; j <= numClasses; j++){
                System.out.println(this.Cal[r][j]);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

声明数组引用变量不会创建数组。该过程的下一步是使用 new 关键字创建数组并将其地址分配给变量。您还应该包括数组的尺寸。

private String[][] cal = new String[5][5];