11-1 Chapter 11 2D Arrays Asserting Java Rick Mercer
11-2 Two-Dimensional Arrays Data is sometimes conveniently viewed as tabular data ( in rows and columns) Quiz Quiz
11-3 Declaring Two-Dimensional Arrays This data can be represented by an array of arrays General Form type [][] identifier = new type [ rows ][ columns ] type [][] identifier = new type [ rows ][ columns ] type: a primitive type or reference type like String type: a primitive type or reference type like String identifier: reference to the two-dimensional array identifier: reference to the two-dimensional array rows: the number of rows allowed rows: the number of rows allowed columns: the number of columns in each row columns: the number of columns in each row Example where all 80 elements are 0 int[][] quiz = new int[8][10];
11-4 Referencing individual elements in a 2-D array Reference to an element of a two-dimensional array requires two subscripts ( row and column) identifier [ row ] [ column ] identifier [ row ] [ column ] Each subscript must be bracketed individually — [ row, column ] is an error — Examples: quiz[0][0] = 76; quiz[1][1] = 91; int sum = quiz[3][4] + quiz[6][7]; quiz[7][9]++;
11-5 Can use array initializers Each of the 10 arrays has 8 integer elements int[][] quiz = { { 76, 82, 78, 85, 56, 72, 84, 92 }, { 86, 91, 92, 100, 48, 68, 92, 78 }, { 76, 82, 48, 95, 76, 72, 78, 92 }, { 86, 91, 78, 73, 48, 98, 90, 78 }, { 76, 82, 78, 35, 56, 72, 84, 92 }, { 86, 100, 92, 100, 48, 68, 92, 68 }, { 76, 82, 48, 65, 76, 72, 78, 94 }, { 86, 91, 78, 0, 48, 98, 90, 76 }, { 76, 82, 48, 95, 76, 72, 78, 92 }, { 100, 92, 100, 100, 86, 92, 98, 99 } }; assertEquals(76, quiz[0][0]); // upper left assertEquals(100, quiz[5][3]); // near middle assertEquals(99, quiz[9][7]); // lower right
11-6 Can ask for rows and columns assertEquals(10, quiz.length); // rows assertEquals(8, quiz[0].length); // columns assertEquals(8, quiz[7].length); // columns
11-7 Display elements row by row // Example of row by row processing for (int row = 0; row < quiz.length; row++) { // Display one row for (int col = 0; col < quiz[0].length; col++) { // Display each column of each row System.out.print(quiz[row][col] + " "); } System.out.println(); } Output
11-8 Other example code See Chapter 11 for more examples of row by row processing and column by column processing using nested for loops Continue code demo with class Matrix