2012-12-15 132 views
2

问题是我试图打印先前在构造函数中创建的矩阵,但似乎是空的。尝试打印数组时尝试在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]); 
} 

问候!

回答

4

通过

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

构造函数初始化并填充一个局部变量代替初始化和填充由print()方法中使用的实例字段的替换

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

+0

感谢您的答案,现在似乎工作,但以一种奇怪的方式。我将维度设置为2x2,但是当我调用print方法时,它会打印如此巨大的数字链......我在构造函数中有什么错误吗? –

+1

@Ziitox你还期望什么?在使用print()方法时,你从不会调用'System.out.println()'或在你的输出中使用''\ n“'。 – jlordo

0

这是怎么一回事,因为你已经声明和初始化构造函数中的阵列randomMatrix并尽快执行构造器的代码,你randomMatrix阵列超出print方法的范围。

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

1

看起来randomMatrix直接在构造函数中的范围界定,并且不被存储在这个班的一个领域。

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

相关问题