/* * T01n23.java -- Demonstrate use and initialization of 2D arrays by * performing a scalar multiplication of a 4x4 matrix. * * As usual, this is a small example and, for use in a real program, its * code should be improved. For instance, because Java 2D arrays can have * rows of varying lengths, the creation of the result array in * the multiplyScalar method isn't adequate; we should create the rows * separately, based on the lengths of the corresponding rows in the * original array. Another example: The printing is nice for the values * created by this program, but it would be much better to write the * printing method to check the sizes of the numbers first and adjust * the output formatting to match. * * Like the books in the library example, it would be more object-oriented * of me to create the 2D matrix as a class and to have these * methods as instances methods of the class. */ import java.util.*; public class T01n23 { public static void main (String [] args) { int[][] destination, // matrix w/ answers original = { { 1, 2, 3, 4}, { 4, 3, 2, 1}, { 0, -5, 9, 6}, { 1, 7, -9, 0} }; // to be multiplied printMatrix(original); destination = multiplyScalar(original,5); printMatrix(destination); } private static void printMatrix (int[][] array) { System.out.println(); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) System.out.printf("%4d",array[i][j]); System.out.println(); } System.out.println(); } private static int[][] multiplyScalar (int[][] array, int value) { int[][] result; // array to hold the result of the scalar product /* The following creation of the array deserves explanation. * As we will (or did!) discuss in class, Java's 2D arrays * are really 1D arrays in which each element is a 1D array. * In a 2D array, array.length can be thought of as the * number of rows of the array. Because each row is a 1D * array, we can find its quantity of elements (columns, in * this case) by accessing its own length field. */ result = new int[array.length][array[0].length]; // see above! for (int i = 0; i < array.length; i++) for (int j = 0; j < array[i].length; j++) result[i][j] = array[i][j] * value; return result; } }