19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7.5 Case Study: Grading a Multiple-Choice Test 271<br />

The key is s<strong>to</strong>red in a one-dimensional array:<br />

Key <strong>to</strong> the Questions:<br />

0 1 2 3 4 5 6 7 8 9<br />

Key D B D C C D A E A D<br />

Your program grades the test and displays the result. It <strong>com</strong>pares each student’s answers with<br />

the key, counts the number of correct answers, and displays it. Listing 7.2 gives the program.<br />

LISTING 7.2<br />

GradeExam.java<br />

1 public class GradeExam {<br />

2 /** Main method */<br />

3 public static void main(String[] args) {<br />

4 // Students' answers <strong>to</strong> the questions<br />

5 char[][] answers = {<br />

6 {'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},<br />

7 {'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},<br />

8 {'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},<br />

9 {'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},<br />

10 {'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},<br />

11 {'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},<br />

12 {'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},<br />

13 {'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};<br />

14<br />

15 // Key <strong>to</strong> the questions<br />

16 char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};<br />

17<br />

18 // Grade all answers<br />

19 for (int i = 0; i < answers.length ; i++) {<br />

20 // Grade one student<br />

21 int correctCount = 0;<br />

22 for (int j = 0; j < answers[i].length ; j++) {<br />

23 if ( answers[i][j] == keys[j] )<br />

24 correctCount++;<br />

25 }<br />

26<br />

27 System.out.println("Student " + i + "'s correct count is " +<br />

28 correctCount);<br />

29 }<br />

30 }<br />

31 }<br />

2-D array<br />

1-D array<br />

<strong>com</strong>pare with key<br />

Student 0's correct count is 7<br />

Student 1's correct count is 6<br />

Student 2's correct count is 5<br />

Student 3's correct count is 4<br />

Student 4's correct count is 8<br />

Student 5's correct count is 7<br />

Student 6's correct count is 7<br />

Student 7's correct count is 7<br />

The statement in lines 5–13 declares, creates, and initializes a two-dimensional array of<br />

characters and assigns the reference <strong>to</strong> answers of the char[][] type.<br />

The statement in line 16 declares, creates, and initializes an array of char values and<br />

assigns the reference <strong>to</strong> keys of the char[] type.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!