我正在写一段涉及矩阵的代码。我的ArrayMatrix代码编译时没有任何错误,但当我试图对代码运行JUnit测试时,我会遇到错误。在这一点上,我不确定我是否做得对。
public class ArrayMatrix extends AbstractMatrix{
private double[][] elements;
public ArrayMatrix(final int rows, final int columns) throws MatrixException{
// Initialise a new matrix with all the elements set to 0.0
if (rows < 0 || columns < 0) {
throw new MatrixException("Negative rows or columns are not allowed");
}
double[][] elements = new double[rows][columns];
int i,j;
for (i=0;i<rows;i++) {
for (j=0;j<columns;j++) {
elements[i][j]= 0.0;
}
}
}
public ArrayMatrix(double[][] content) throws MatrixException{
// Initialise a new matrix storing the data provided by the
// double[][] parameter. Note the data should be copied.
int rows = elements.length;
int columns = elements[0].length;
int i,j;
for (i=0;i<rows;i++) {
for(j=0;j<columns;j++) {
content[i][j] = elements[i][j];
}
}
}
public int getNumberOfRows(){
// Number of rows in matrix
int noRows = elements.length;
return noRows;
}
public int getNumberOfColumns(){
// Number of columns in matrix
int noColumns = elements[0].length;
return noColumns;
}
public double getElement(final int row, final int column) throws MatrixException{
// Return the element at the specified position or throw an exception
if (elements.length<=row) {
throw new MatrixException("Attempt to access invalid element ("+row+","+column+")");
}
if (elements[0].length<column){
throw new MatrixException("Attempt to access invalid element ("+row+","+column+")");
}
else {return elements[row][column];}
}
public void setElement(final int row, final int column, final double value) throws MatrixException{
// Set the element at the specified position or throw an exception
if (elements.length<=row) {
throw new MatrixException("Attempt to access invalid element ("+row+","+column+")");}
if (elements[0].length<column){
throw new MatrixException("Attempt to access invalid element ("+row+","+column+")");}
else {elements[row][column] = value;}
}
}
这是我写的JUnit测试:
@Test
public void testGetNumberOfRows() throws MatrixException {
ArrayMatrix a = new ArrayMatrix(2, 2);
int output = a.getNumberOfRows();
assertEquals(2,output);
我是否写错了JUnit测试?
getNumberOfRows()
方法中的代码抛出一个NullPointerException
。这是因为您没有在构造函数中初始化MatrixArrays的elements
数组,它保持为null
,并且当您尝试访问null的属性(length
(时会引发异常。
相反,您在构造函数中使用double[][] elements = new double[rows][columns];
创建了一个新的局部变量,这可能不是有意的。
将该行替换为对MatrixArray字段(在构造函数中(的引用:this.elements = new double[rows][columns];
。现在elements
数组已经初始化,您应该能够毫无例外地访问它的字段。
顺便说一句,在构造函数ArrayMatrix(double[][])
中也有类似的问题:您也应该考虑一下。