public class Matrix { private int rows = 0; private int columns = 0; private int[][] matrix; Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.init(); } private void init() { this.matrix = new int[this.rows][this.columns]; for(int r = 0; r < this.rows; r++) { for(int c = 0; c < this.columns; c++) { this.setValue(r+1, c+1, 0); } } } int getValue(int row, int column) { return this.matrix[row-1][column-1]; } int getNumberOfColumns() { return this.columns; } int getNumberOfRows() { return this.rows; } void setValue(int row, int column, int value) { this.matrix[row-1][column-1] = value; } void multiply(int scalar) { for(int r = 0; r < this.rows; r++) { for(int c = 0; c < this.columns; c++) { this.matrix[r][c] *= scalar; } } } void multiply(Matrix matrix) { if(isSameSize(matrix)) { for(int r = 0; r < this.rows; r++) { for(int c = 0; c < this.columns; c++) { this.matrix[r][c] *= matrix.getValue(r+1, c+1); } } } else { throw new MatrixException(); } } boolean isSameSize(Matrix matrix) { return this.getNumberOfColumns() == matrix.getNumberOfColumns() && this.getNumberOfRows() == matrix.getNumberOfRows(); } void add(Matrix matrix) { if(this.getNumberOfColumns() == matrix.getNumberOfColumns() && this.getNumberOfRows() == matrix.getNumberOfRows()) { for(int r = 0; r < this.rows; r++) { for(int c = 0; c < this.columns; c++) { this.matrix[r][c] += matrix.getValue(r+1, c+1); } } } } void print() { for(int r = 0; r < this.rows; r++) { for(int c = 0; c < this.columns; c++) { System.out.printf("%5d", this.getValue(r+1, c+1)); } System.out.print("\n"); } } } class MatrixException extends RuntimeException { }