Java Reference
In-Depth Information
The key is stored in a one-dimensional array:
Key to the Questions:
0 1 2 3 4 5 6 7 8 9
Key D B D C C D A E A D
Your program grades the test and displays the result. It compares each student's answers with
the key, counts the number of correct answers, and displays it. Listing 7.2 gives the program.
L
ISTING
7.2
GradeExam.java
1
public class
GradeExam {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Students' answers to the questions
5
6
7
8
9
10
11
12
13
14
15
char
[][] answers = {
2-D array
{
'A'
,
'B'
,
'A'
,
'C'
,
'C'
,
'D'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'D'
,
'B'
,
'A'
,
'B'
,
'C'
,
'A'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'E'
,
'D'
,
'D'
,
'A'
,
'C'
,
'B'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'C'
,
'B'
,
'A'
,
'E', 'D'
,
'C'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'A'
,
'B'
,
'D'
,
'C'
,
'C'
,
'D'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'B'
,
'B'
,
'E'
,
'C'
,
'C'
,
'D'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'B'
,
'B'
,
'A'
,
'C'
,
'C'
,
'D'
,
'E'
,
'E'
,
'A'
,
'D'
},
{
'E'
,
'B'
,
'E'
,
'C'
,
'C'
,
'D'
,
'E'
,
'E'
,
'A'
,
'D'
}};
// Key to the questions
16
17
18
char
[] keys = {
'D'
,
'B'
,
'D'
,
'C'
,
'C'
,
'D'
,
'A'
,
'E'
,
'A'
,
'D'
};
1-D array
// Grade all answers
19
for
(
int
i =
0
;
i < answers.length
; i++) {
20
// Grade one student
21
int
correctCount =
0
;
22
for
(
int
j =
0
;
j < answers[i].length
; j++) {
23
if
(
answers[i][j] == keys[j]
)
compare with key
24 correctCount++;
25 }
26
27 System.out.println(
"Student "
+ i +
"'s correct count is "
+
28 correctCount);
29 }
30 }
31 }
Student 0's correct count is 7
Student 1's correct count is 6
Student 2's correct count is 5
Student 3's correct count is 4
Student 4's correct count is 8
Student 5's correct count is 7
Student 6's correct count is 7
Student 7's correct count is 7
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.