Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table.
Here is the syntax for declaring a two-dimensional array:
dataType[][] arrayRefVar;
or
dataType arrayRefVar[][]; // This style is allowed, but not preferred
As an example, here is how you would declare a two-dimensional array variable matrix of int values:
int [][] matrix;
or
int matrix[][]; // This style is allowed, but not preferred
You can create a two-dimensional array of 5 by 5 int values and assign it to matrix using this syntax:
matrix = new int [ 5 ][ 5 ];
Two subscripts are used in a two-dimensional array, one for the row, and the other for the column. As in a one-dimensional array, the index for each subscript is of the int type and starts from 0, as shown in Figure 6.15(a).
To assign the value 7 to a specific element at row 2 and column 1 , as shown in Figure 6.15(b), you can use the following:
matrix[ 2 ][ 1 ] = 7 ;
Caution
It is a common mistake to use matrix[2, 1] to access the element at row 2 and column 1 . In Java, each subscript must be enclosed in a pair of square brackets. |
You can also use an array initializer to declare, create, and initialize a two-dimensional array. For example, the following code in (a) creates an array with the specified initial values, as shown in Figure 6.15(c). This is equivalent to the code in (b).
A two-dimensional array is actually an array in which each element is a one-dimensional array. The length of an array x is the number of elements in the array, which can be obtained using x.length . x[0] , x[1] , ..., and x[x.length-1] are arrays. Their lengths can be obtained using x[0].length , x[1].length , ..., and x[x.length-1].length .
For example, suppose x = new int[3][4] , x[0] , x[1] , and x[2] are one-dimensional arrays and each contains four elements, as shown in Figure 6.16. x.length is 3 , and x[0].length , x[1].length , and x[2].length are 4 .
Each row in a two-dimensional array is itself an array. Thus the rows can have different lengths. An array of this kind is known as a ragged array . Here is an example of creating a ragged array:
As can be seen, triangleArray[0].length is 5 , triangleArray[1].length is 4 , triangleArray[2].length is 3 , triangleArray[3].length is 2 , and triangleArray[4].length is 1 .
If you don't know the values in a ragged array in advance, but you know the sizes, say the same as before, you can create a ragged array using the syntax that follows :
int [][] triangleArray = new int [5][] ; triangleArray[ ] = new int[ 5 ]; triangleArray[ 1 ] = new int[ 4 ]; triangleArray[ 2 ] = new int[ 3 ]; triangleArray[ 3 ] = new int[ 2 ]; triangleArray[ 4 ] = new int[ 1 ];
You can now assign values to the array. For example,
triangleArray[ ][ 3 ] = 50 ; triangleArray[ 4 ][ ] = 45 ;
Note
The syntax new int[5][] for creating an array requires the first index to be specified. The syntax new int[][] would be wrong. |
Suppose an array matrix is declared as follows:
int [][] matrix = new int [ 10 ][ 10 ];
Here are some examples of processing two-dimensional arrays:
( Initializing arrays with random values ) The following loop initializes the array with random values between and 99 :
for ( int row = ; row < matrix.length ; row++) { for ( int column = ; column < matrix[row].length ; column++) { matrix[row][column] = (int)(Math.random() * 100 ); } }
( Printing arrays ) To print a two-dimensional array, you have to print each element in the array using a loop like the following:
for ( int row = ; row < matrix.length ; row++) { for (int column = ; column < matrix[row].length ; column++) { System.out.print(matrix[row][column] + " " ); } System.out.println(); }
( Summing all elements ) Use a variable named total to store the sum. Initially total is . Add each element in the array to total using a loop like this:
int total = ; for ( int row = ; row < matrix.length; row++) { for ( int column = ; column < matrix[row].length; column++) { total += matrix[row][column]; } }
( Summing elements by column ) For each column, use a variable named total to store its sum. Add each element in the column to total using a loop like this:
for ( int column = ; column < matrix[ ].length; column++) { int total = ; for ( int row = ; row < matrix.length; row++)
total += matrix[row][column]; System.out.println( "Sum for column " + column + " is " + total); }
( Which row has the largest sum? ) Use variables maxRow and indexOfMaxRow to track the largest sum and index of the row. For each row, compute its sum, and update maxRow and indexOfMaxRow if the new sum is greater.
int maxRow = ; int indexOfMaxRow = ; // Get sum of the first row in maxRow for ( int column = ; column < matrix[ ].length; column++) { maxRow += matrix[ ][column]; } for ( int row = 1 ; row < matrix.length; row++) { int totalOfThisRow = ; for ( int column = ; column < matrix[row].length; column++) { totalOfThisRow += matrix[row][column]; if (totalOfThisRow > maxRow) { maxRow = totalOfThisRow; indexOfMaxRow = row; } } } System.out.println( "Row " + indexOfMaxRow + " has the maximum sum" + " of " + maxRow);
This example presents a program that grades multiple-choice tests. Suppose there are eight students and ten questions, and the answers are stored in a two-dimensional array. Each row records a student's answers to the questions. For example, the array shown below stores the test.
The key is stored in a one-dimensional array:
Your program grades the test and displays the result, as shown in Figure 6.17.
The program compares each student's answers with the key, counts the number of correct answers, and displays it. Listing 6.10 gives the program.
1 public class GradeExam { 2 /** Main method */ 3 public static void main(String args[]) { 4 // Students' answers to the questions 5 char [][] answers = { 6 {' A ', ' B ', ' A ', ' C ', ' C ', ' D ', ' E ', ' E ', ' A ', ' D '}, 7 {' D ', ' B ', ' A ', ' B ', ' C ', ' A ', ' E ', ' E ', ' A ', ' D '}, 8 {' E ', ' D ', ' D ', ' A ', ' C ', ' B ', ' E ', ' E ', ' A ', ' D '}, 9 {' C ', ' B ', ' A ', ' E ', ' D ', ' C ', ' E ', ' E ', ' A ', ' D '}, 10 {' A ', ' B ', ' D ', ' C ', ' C ', ' D ', ' E ', ' E ', ' A ', ' D '}, 11 {' B ', ' B ', ' E ', ' C ', ' C ', ' D ', ' E ', ' E ', ' A ', ' D '}, 12 {' B ', ' B ', ' A ', ' C ', ' C ', ' D ', ' E ', ' E ', ' A ', ' D '}, 13 {' E ', ' B ', ' E ', ' C ', ' C ', ' D ', ' E ', ' E ', ' A ', ' D '}}; 14 15 // Key to the questions 16 char [] keys = {' D ', ' B ', ' D ', ' C ', ' C ', ' D ', ' A ', ' E ', ' A ', ' D '}; 17 18 // Grade all answers 19 for ( int i = ; i < answers.length ; i++) { 20 // Grade one student 21 int correctCount = ; 22 for ( int j = ; j < answers[i].length ; j++) { 23 if ( answers[i][j] == keys[j] ) 24 correctCount++; 25 } 26 27 System.out.println( "Student " + i + "'s correct count is " + 28 correctCount); 29 } 30 } 31 } |
The statement in lines 5 “13 declares, creates, and initializes a two-dimensional array of characters and assigns the reference to answers of the char[][] type.
The statement in line 16 declares, creates, and initializes an array of char values and assigns the reference to keys of the char[][] type.
Each row in the array answers stores a student's answer, which is graded by comparing it with the key in the array keys . The result is displayed immediately after a student's answer is graded.
6.10.6. (Optional) Example: Computing Taxes |
Listing 5.5, ComputeTaxWithMethod.java, simplified Listing 3.4, ComputeTaxWithSelectionStatement.java. Listing 5.5 can be further improved using arrays. For each filing status, there are six tax rates. Each rate is applied to a certain amount of taxable income. For example, from the taxable income of $400,000 for a single filer , $6,000 is taxed at 10%, at 15%, at 27%, at 30%, at 35%, and at 38.6%. The six rates are the same for all filing statuses, which can be represented in the following array:
double [] rates = { 0.10 , 0.15 , 0.27 , 0.30 , 0.35 , 0.386 };
The brackets for each rate for all the filing statuses can be represented in a two-dimensional array as follows:
int [][] brackets = { { 6000 , 27950 , 67700 , 141250 , 307050 }, // Single filer { 12000 , 46700 , 112850 , 171950 , 307050 }, // Married jointly { 6000 , 23350 , 56425 , 85975 , 153525 }, // Married separately { 10000 , 37450 , 96700 , 156600 , 307050 } // Head of household };
Suppose the taxable income is $400,000 for single filers, the tax can be computed as follows:
brackets[ ][ ] * rates[ ] + (brackets[ ][ 1 ] “ brackets[ ][ ]) * rates[ 1 ] + (brackets[ ][ 2 ] “ brackets[ ][ 1 ]) * rates[ 2 ] + (brackets[ ][ 3 ] “ brackets[ ][ 2 ]) * rates[ 3 ] + (brackets[ ][ 4 ] “ brackets[ ][ 3 ]) * rates[ 4 ] + ( 400000 “ brackets[ ][ 4 ]) * rates[ 5 ]
Listing 6.11 gives the solution to the program.
1 import javax.swing.JOptionPane; 2 3 public class ComputeTax { 4 public static void main(String[] args) { 5 // Prompt the user to enter filing status 6 String statusString = JOptionPane.showInputDialog( 7 "Enter the filing status:\n" + 8 "(0-single filer, 1-married jointly,\n" + 9 "2-married separately, 3-head of household)" ); 10 int status = Integer.parseInt(statusString); 11 12 // Prompt the user to enter taxable income 13 String incomeString = JOptionPane.showInputDialog( 14 "Enter the taxable income:" ); 15 double income = Double.parseDouble(incomeString); 16 17 // Compute and display the result 18 JOptionPane.showMessageDialog( null , "Tax is " + 19 ( int )( computeTax(status, income) * 100 ) / 100.0 ); 20 } 21 22 public static double computeTax( int status, double income) { 23 double [] rates = { 0.10 , 0.15 , 0.27 , 0.30 , 0.35 , 0.386 }; 24 25 int [][] brackets = { 26 { 6000 , 27950 , 67700 , 141250 , 307050 }, // Single filer 27 { 12000 , 46700 , 112850 , 171950 , 307050 }, // Married jointly 28 { 6000 , 23350 , 56425 , 85975 , 153525 }, // Married separately 29 { 10000 , 37450 , 96700 , 156600 , 307050 } // Head of household 30 }; 31 32 double tax = ; // Tax to be computed 33 34 // Compute tax in the first bracket 35 if (income <= brackets[status][ ]) 36 return tax = income * rates[ ]; //Done 37 else 38 tax = brackets[status][ ] * rates[ ]; 39 40 // Compute tax in the 2nd, 3rd, 4th, and 5th brackets, if needed 41 for ( int i = 1 ; i < brackets[0].length; i++) { 42 if (income > brackets[status][i]) 43 tax += (brackets[status][i] - brackets[status][i - 1 ]) * 44 rates[i]; 45 else { 46 tax += (income - brackets[status][i - 1 ]) * rates[i]; 47 return tax; // Done 48 } 49 } 50 51 // Compute tax in the last (i.e., 6th) bracket 52 return tax += (income - brackets[status][ 4 ]) * rates[ 5 ]; 53 } 54 } |
The computeTax method computes the tax for the taxable income of a given filing status. The tax for the first bracket ( to brackets[status][0] ) is computed in lines 35 “38. The taxes for the second, third, fourth, and fifth brackets are computed in the loop in lines 41 “49. The tax for the last bracket is computed in line 52.