C.10. Case Study: Nested Control Statements

We’ve seen that control statements can be stacked on top of one another (in sequence). In this case study, we examine the only other structured way control statements can be connected—nesting one control statement within another.

Consider the following problem statement:

A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, ten of the students who completed this course took the exam.

The college wants to know how well its students did on the exam. You’ve been asked to write a program to summarize the results. You’ve been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or a 2 if the student failed.

Your program should analyze the results of the exam as follows:

1. Input each test result (i.e., a 1 or a 2). Display the message “Enter result” on the screen each time the program requests another test result.

2. Count the number of test results of each type.

3. Display a summary of the test results, indicating the number of students who passed and the number who failed.

4. If more than eight students passed the exam, print the message “Bonus to instructor!”

The complete pseudocode appears in Fig. C.7. The Java class that implements the pseudocode algorithm and two sample executions are shown in Fig. C.8. Lines 13–16 of main declare the variables that method processExamResults of class Analysis uses to process the examination results. Several of these declarations use Java’s ability to incorporate variable initialization into declarations (passes is assigned 0, failures 0 and studentCounter 1). Looping programs may require initialization at the beginning of each repetition—normally performed by assignment statements rather than in declarations. Java requires that local variables be initialized before their values are used in an expression.


 1   Initialize passes to zero
 2   Initialize failures to zero
 3   Initialize student counter to one
 4
 5   While student counter is less than or equal to 10
 6      Prompt the user to enter the next exam result
 7      Input the next exam result
 8
 9      If the student passed
10         Add one to passes
11      Else
12         Add one to failures
13
14      Add one to student counter
15
16   Print the number of passes
17   Print the number of failures
18
19   If more than eight students passed
20      Print "Bonus to instructor!"


Fig. C.7 | Pseudocode for examination-results problem.


 1   // Fig. C.8: Analysis.java
 2   // Analysis of examination results using nested control statements.
 3   import java.util.Scanner; // class uses class Scanner
 4
 5   public class Analysis
 6   {
 7      public static void main( String[] args )
 8      {
 9         // create Scanner to obtain input from command window
10         Scanner input = new Scanner( System.in );
11
12         // initializing variables in declarations 
13         int passes = 0; // number of passes       
14         int failures = 0; // number of failures   
15         int studentCounter = 1; // student counter
16         int result; // one exam result (obtains value from user)
17
18         // process 10 students using counter-controlled loop
19         while ( studentCounter <= 10 )
20         {
21            // prompt user for input and obtain value from user
22            System.out.print( "Enter result (1 = pass, 2 = fail): " );
23            result = input.nextInt();
24
25            // if...else is nested in the while statement          
26            if ( result == 1 )          // if result 1,            
27               passes = passes + 1;     // increment passes;       
28            else                        // else result is not 1, so
29               failures = failures + 1; // increment failures      
30
31            // increment studentCounter so loop eventually terminates
32            studentCounter = studentCounter + 1 ;
33         } // end while
34
35         // termination phase; prepare and display results
36         System.out.printf( "Passed: %d Failed: %d ", passes, failures );
37
38         // determine whether more than 8 students passed
39         if ( passes > 8 )                               
40            System.out.println( "Bonus to instructor!" );
41      } // end main
42   } // end class Analysis

Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Passed: 9
Failed: 1
Bonus to instructor!


Fig. C.8 | Analysis of examination results using nested control statements.

The while statement (lines 19–33) loops 10 times. During each iteration, the loop inputs and processes one exam result. Notice that the if...else statement (lines 26–29) for processing each result is nested in the while statement. If the result is 1, the if...else statement increments passes; otherwise, it assumes the result is 2 and increments failures. Line 32 increments studentCounter before the loop condition is tested again at line 19. After 10 values have been input, the loop terminates and line 36 displays the number of passes and failures. The if statement at lines 39–40 determines whether more than eight students passed the exam and, if so, outputs the message "Bonus to instructor!".

During the sample execution, the condition at line 39 of method main is true—more than eight students passed the exam, so the program outputs a message to bonus the instructor.

This example contains only one class, with method main performing all the class’s work. Occasionally, when it does not make sense to try to create a reusable class to demonstrate a concept, we’ll place the program’s statements entirely within the main method of a single class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset