CASE STUDY^609
{
returnmatrix[ 0 ].length;
}
The main transformer method takes a value and a row and column number. The
value is stored into the matrix at the [row][column] position.
public voidsetValue(doubledataItem, introw, intcol)
// Sets matrix[row][col] to dataItem
{
matrix[row][col] = dataItem;
}
The remaining observer isprintMatrix. We want to print the matrix by row. We have a
pattern that we can follow exactly from our general discussion about arrays. Because we
don’t know how many columns the matrix has, we should print a blank line between rows.
public voidprintMatrix(PrintWriter outFile)
// Prints matrix on outFile by row
{
for(introw = 0 ; row < matrix.length; row++)
{
for(intcol = 0 ; col < matrix[ 0 ].length; col++)
outFile.print(matrix[row][col] + " ");
outFile.println();
outFile.println();
}
}
The last three methods lie at the heart of this problem: adding, subtracting, and mul-
tiplying matrices. One matrix is the one to which the method is applied and the other
matrix is a parameter.
Each of these steps is concrete. Determining if the addition is legal is a matter of
checking the dimensions of matrixagainst the dimensions of the parameter. The string
that goes with the exception can simply state that the addition is not legal.
add(two)
ifthe addition is not legal
throw MatException
else
Create result matrix with the same dimensions as matrix
forrow going from 0 through matrix.length – 1
forcol going from 0 through matrix[0].length – 1
Set result[row][col] to matrix[row][col] + two.matrix[row][col]
returnresult