Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


614


publicMatrix add(Matrix two) throwsMatException
// Returns the sum of matrix and two.matrix
// Throws MatException if the matrices cannot be added
// or overflow occurs
{
if(matrix.length != two.matrix.length ||
matrix[ 0 ].length != two.matrix[ 0 ].length)
throw newMatException("Illegal matrix add.");
else
{
Matrix result =
newMatrix(matrix.length, matrix[ 0 ].length);
for(introw = 0 ; row < matrix.length; row++)
for(intcol = 0 ; col < matrix[ 0 ].length; col++)
{
result.matrix[row][col] = matrix[row][col] +
two.matrix[row][col];
if(Double.isInfinite(result.matrix[row][col]))
throw newMatException("Addition overflow");
}
returnresult;
}
}

publicMatrix sub(Matrix two) throwsMatException
// Returns two.matrtix subtracted from matrix
// Throws MatException if the matrices cannot be subtracted
// or overflow occurs
{
if(matrix.length != two.matrix.length ||
matrix[ 0 ].length != two.matrix[ 0 ].length)
throw newMatException("Illegal matrix subtract.");
else
{
Matrix result =
newMatrix(matrix.length, matrix[ 0 ].length);
for(introw = 0 ; row < matrix.length; row++)
for(intcol = 0 ; col < matrix[ 0 ].length; col++)
{
result.matrix[row][col] =
matrix[row][col] – two.matrix[row][col];
if(Double.isInfinite(result.matrix[row][col]))
throw newMatException("Subtraction overflow");
}
Free download pdf