【问题标题】:NullPointerException in Java while trying to print an array尝试打印数组时Java中的NullPointerException
【发布时间】:2012-12-15 16:11:12
【问题描述】:

问题是我正在尝试打印之前在构造函数中创建的矩阵,但它似乎是空的。

这是构造函数的代码:

public Matrix(int row_col){
    int [][] randomMatrix = new int[row_col][row_col];
    Random rand = new Random();
    if (row_col > 0 && row_col < ROW_LIMIT && row_col < COL_LIMIT)
    for (int i = 0; i < randomMatrix.length; i++) 
     for (int j = 0; j < randomMatrix[0].length; j++)
         randomMatrix[i][j] = rand.nextInt(51);
}

以及方法print的代码:

public void print(){
    int row = randomMatrix.length;
    int col = randomMatrix[0].length;
    for(int i=0 ; i < row ; i++)
     for(int j=0 ; j < col ; j++)
        System.out.print(randomMatrix[i][j]);
}

您好!

【问题讨论】:

    标签: java arrays exception nullpointerexception


    【解决方案1】:

    替换

    int [][] randomMatrix = new int[row_col][row_col];
    

    通过

    this.randomMatrix = new int[row_col][row_col];
    

    构造函数初始化并填充一个局部变量,而不是初始化和填充print()方法使用的实例字段

    【讨论】:

    • 感谢您的回答,现在似乎可以工作了,但是方式很奇怪。我将尺寸设置为 2x2,但是当我调用 print 方法时,它会打印出如此巨大的数字链......我的构造函数有什么问题吗?
    • @Ziitox 你还期待什么?使用 print() 方法时,您永远不会调用 System.out.println() 或在输出中包含 "\n"
    【解决方案2】:

    看起来 randomMatrix 是直接在构造函数的范围内定义的,而不是存储在类的字段中。

    如果您已经有一个 randomMatrix 作为字段,请删除构造方法的第一行中的 int[][],这样您就可以引用该字段而不是声明一个新变量。

    【讨论】:

      【解决方案3】:

      这是因为您已经在构造函数中声明并初始化了数组 randomMatrix,并且一旦执行构造函数的代码,您的 randomMatrix 数组就会超出 print 方法的范围。

      所以当你尝试在print 方法中访问它时,没有这样的randomMatrix 对象,所以你得到NullPointerException

      【讨论】:

        猜你喜欢
        • 2014-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-20
        • 2014-05-29
        • 2018-10-24
        • 1970-01-01
        • 2016-01-26
        相关资源
        最近更新 更多