70 likes | 280 Views
Chapter 11 2D Arrays. Asserting Java Rick Mercer. Two-Dimensional Arrays. Data is sometimes conveniently viewed as tabular data ( in rows and columns) Quiz 1 2 3 4 5 6 7 8 76 82 78 85 56 72 84 92 86 91 92 100 48 68 92 78
E N D
Chapter 11 2D Arrays Asserting Java Rick Mercer
Two-Dimensional Arrays • Data is sometimes conveniently viewed as tabular data (in rows and columns) • Quiz 1 2 3 4 5 6 7 8 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
Declaring Two-Dimensional Arrays • This data can be represented by an array of arrays • General Form type [][]identifier = newtype[rows][columns] type: a primitive type or reference type like String identifier: reference to the two-dimensional array rows: the number of rows allowed columns: the number of columns in each row • Example where all 80 elements are 0 int[][] quiz = newint[8][10];
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 ] • 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]++;
Can use array initializersEach 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
Can ask for rows and columns • assertEquals(10, quiz.length); // rows • assertEquals(8, quiz[0].length); // columns • assertEquals(8, quiz[7].length); // columns
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 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