问题是我试图打印先前在构造函数中创建的矩阵,但似乎是空的。尝试打印数组时尝试在Java中出现NullPointerException
这里的构造函数的代码:
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);
}
而且方法打印的代码:
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]);
}
问候!
感谢您的答案,现在似乎工作,但以一种奇怪的方式。我将维度设置为2x2,但是当我调用print方法时,它会打印如此巨大的数字链......我在构造函数中有什么错误吗? –
@Ziitox你还期望什么?在使用print()方法时,你从不会调用'System.out.println()'或在你的输出中使用''\ n“'。 – jlordo