What does the folowing code print out after the prompt(s)? DO NOT RUN THIS CODE. Try and figure out what it does just by looking at it. You are not graded on correctness, this is purely to help you understand java. |
public class Matrix { int[][] data; Matrix( int[][] matrixData ){ this.data = new int[matrixData.length][matrixData[0].length]; for( int row = 0; row < matrixData.length; ++row){ for( int col = 0; col < matrixData[0].length; ++col){ this.data[row][col] = matrixData[row][col]; } } } public int getRows(){ return this.data.length; } public int getColumns(){ return this.data[0].length; //we can assume that 2D array is rectangular } public int getDataAt( int row, int column ){ return this.data[row][column]; } public int[][] addMatrix( Matrix otherMatrix ) { if( this.getRows() != otherMatrix.getRows() || this.getColumns() != otherMatrix.getColumns() ){ System.out.println("Matrices must be same size"); System.out.println( "this Matrix: "+ this.getRows() + " rows "+ this.getColumns() + " columns"); System.out.println( "otherMatrix: "+ otherMatrix.getRows() + " rows, "+ otherMatrix.getColumns()+ " columns"); System.exit(-1); } int[][] additionData = new int[this.getRows()][this.getColumns()]; for( int row = 0; row < this.getRows(); ++row ){ for( int col = 0; col < this.getColumns(); ++col){ additionData[row][col] = this.getDataAt(row, col) + otherMatrix.getDataAt(row, col); } } return additionData; } public void transpose(){ int[][] transposeData = new int[this.getColumns()][this.getRows()]; for( int row = 0; row< this.getRows(); ++row){ for( int col = 0; col < this.getColumns(); ++col){ transposeData[col][row] = this.getDataAt(row, col); } } this.data = transposeData; } public String toString(){ String output = ""; for( int row = 0; row < this.getRows(); ++row ){ for( int col = 0; col < this.getColumns(); ++col){ output += this.getDataAt(row, col) + ", "; } output += "\n"; } return output; } public static void main(String[] args) { int[][] matrixAData = { {1, 2}, {3, 4}, {5, 6} }; int[][] matrixBData = { {7, 8 }, {9, 10}, {11, 12} }; Matrix matrixA = new Matrix( matrixAData ); Matrix matrixB = new Matrix( matrixBData ); Matrix additionMatrix = new Matrix( matrixA.addMatrix( matrixB ) ); System.out.println( matrixA.toString() ); System.out.println( matrixB.toString() ); System.out.println( additionMatrix.toString() ); matrixA.transpose(); System.out.println( matrixA.toString() ); Matrix transAddMatrix = new Matrix( matrixA.addMatrix( matrixB ) ); System.out.println( transAddMatrix.toString() ); } }Write your answer down (you should have 18 lines of output, including blank lines) and your TA will go over it once everyone has finished.
// returns true if this matrix is an identity matrix
public boolean isIdentity( ){ }