Java Reference
In-Depth Information
23
return m;
return array
24 }
25
26 public static int sum( int [][] m) {
27 int total = 0 ;
28 for ( int row = 0 ; row < m.length; row++) {
29 for ( int column = 0 ; column < m[row].length; column++) {
30 total += m[row][column];
31 }
32 }
33
34
sum method
return total;
35 }
36 }
Enter 3 rows and 4 columns:
1 2 3 4
5 6 7 8
9 10 11 12
Sum of all elements is 78
The method getArray prompts the user to enter values for the array (lines 11-24) and
returns the array (line 23).
The method sum (lines 26-35) has a two-dimensional array argument. You can obtain the
number of rows using m.length (line 28) and the number of columns in a specified row using
m[row].length (line 29).
8.7
Show the output of the following code:
Check
Point
public class Test {
public static void main(String[] args) {
int [][] array = {{ 1 , 2 , 3 , 4 }, { 5 , 6 , 7 , 8 }};
System.out.println(m1(array)[ 0 ]);
System.out.println(m1(array)[ 1 ]);
}
public static int[] m1( int [][] m) {
int [] result = new int [ 2 ];
result[ 0 ] = m.length;
result[ 1 ] = m[ 0 ].length;
return result;
}
}
8.5 Case Study: Grading a Multiple-Choice Test
The problem is to write a program that will grade multiple-choice tests.
Key
Point
Suppose you need to write a program that grades multiple-choice tests. Assume 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, as shown in the following array.
VideoNote
Grade multiple-choice test
 
 
 
Search WWH ::




Custom Search