/* * Matrix addition - complete the add method below * see expected output at end * @author */ public class Matrix { //Return true if matrix is "ragged", ie. not all rows //have the same number of values (columns) //false otherwise public static boolean isRagged(int[][] matrix) { if (matrix.length == 0) return false; int cols = matrix[0].length; for (int i = 1; i < matrix.length; i++) if (matrix[i].length != cols) return true; return false; } //Output the matrix values one row per line public static void output(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] < 10) System.out.print(" " + matrix[i][j]); else System.out.print(" " + matrix[i][j]); } System.out.println(); } } //Return a matrix that is the sum of m1 and m2 //if m1 and m2 have the same number of rows and //cols and are not "ragged" or empty //otherwise return null public static int[][] add(int[][] m1, int[][] m2) { } public static void main(String[] args) { int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}}; int[][] matrix2 = {{9, 3, 5}, {0, 3, 8}}; int[][] matrix3 = {{1, 4}, {2, 3, 5}, {4}}; System.out.println("\nMatrix 1: "); output(matrix1); System.out.println("\nMatrix 2: "); output(matrix2); System.out.println("\nMatrix 3(not really a \"matrix\"): "); output(matrix3); System.out.println("\nMatrix 1 is ragged: " + isRagged(matrix1)); System.out.println("\nMatrix 3 is ragged: " + isRagged(matrix3)); int[][] sum = add(matrix1, matrix2); System.out.println("\nMatrix 1 + Matrix 2: " ); output(sum); } } /* eos% java Matrix Matrix 1: 1 2 3 4 5 6 Matrix 2: 9 3 5 0 3 8 Matrix 3(not really a "matrix"): 1 4 2 3 5 4 Matrix 1 is ragged: false Matrix 3 is ragged: true Matrix 1 + Matrix 2: 10 5 8 4 8 14 */