.NODE

Formulating Algorithms: Nested Control Statements

Formulating Algorithms Nested Control Statements

For the next example, we once again formulate an algorithm by using pseudocode and top-down, stepwise refinement, and write a corresponding Java program. We have seen that control statements can be stacked on top of one another (in sequence) just as a child stacks building blocks. In this case study, we examine the only other structured way control statements can be connected, namely, by 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 have been asked to write a program to summarize the results. You have 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 "Raise tuition."

After reading the problem statement carefully, we make the following observations:

  1. The program must process test results for 10 students. A counter-controlled loop can be used because the number of test results is known in advance.
  2. Each test result has a numeric valueeither a 1 or a 2. Each time the program reads a test result, the program must determine whether the number is a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it is a 2. (Exercise 4.24 considers the consequences of this assumption.)
  3. Two counters are used to keep track of the exam resultsone to count the number of students who passed the exam and one to count the number of students who failed the exam.
  4. After the program has processed all the results, it must decide whether more than eight students passed the exam.

Let us proceed with top-down, stepwise refinement. We begin with a pseudocode representation of the top:


      Analyze exam results and decide whether tuition should be raised

Once again, the top is a complete representation of the program, but several refinements are likely to be needed before the pseudocode can evolve naturally into a Java program.

Our first refinement is


      Initialize variables
      Input the 10 exam results, and count passes and failures
      Print a summary of the exam results and decide whether tuition should be raised

Here, too, even though we have a complete representation of the entire program, further refinement is necessary. We now commit to specific variables. Counters are needed to record the passes and failures, a counter will be used to control the looping process and a variable is needed to store the user input. The variable in which the user input will be stored is not initialized at the start of the algorithm, because its value is read from the user during each iteration of the loop.

The pseudocode statement


      Initialize variables

can be refined as follows:


      Initialize passes to zero
      Initialize failures to zero
      Initialize student counter to one

Notice that only the counters are initialized at the start of the algorithm.

The pseudocode statement


      Input the 10 exam results, and count passes and failures

requires a loop that successively inputs the result of each exam. We know in advance that there are precisely 10 exam results, so counter-controlled looping is appropriate. Inside the loop (i.e., nested within the loop), a double-selection structure will determine whether each exam result is a pass or a failure and will increment the appropriate counter. The refinement of the preceding pseudocode statement is then


      While student counter is less than or equal to 10
          Prompt the user to enter the next exam result
          Input the next exam result

          If the student passed
                 Add one to passes
          Else
                 Add one to failures

          Add one to student counter

We use blank lines to isolate the If...Else control structure, which improves readability.

The pseudocode statement


      Print a summary of the exam results and decide whether tuition should be raised

can be refined as follows:


      Print the number of passes
      Print the number of failures

      If more than eight students passed
           Print "Raise tuition"

Complete Second Refinement of Pseudocode and Conversion to Class Analysis

The complete second refinement of the pseudocode appears in Fig. 4.11. Notice that blank lines are also used to set off the While structure for program readability. This pseudocode is now sufficiently refined for conversion to Java. The Java class that implements the pseudocode algorithm is shown in Fig. 4.12, and two sample executions appear in Fig. 4.13.

Figure 4.11. Pseudocode for examination-results problem.


 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 "Raise tuition"

Figure 4.12. Nested control structures: Examination-results problem.

(This item is displayed on page 151 in the print version)

 1 // Fig. 4.12: Analysis.java
 2 // Analysis of examination results.
 3 import java.util.Scanner; // class uses class Scanner
 4
 5 public class Analysis
 6 {
 7 public void processExamResults
 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 nested in while 
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( "Raise Tuition" );
41 } // end method processExamResults
42
43 } // end class Analysis

Figure 4.13. Test program for class Analysis (Fig. 4.12).

(This item is displayed on pages 152 - 153 in the print version)

 1 // Fig. 4.13: AnalysisTest.java
 2 // Test program for class Analysis.
 3
 4 public class AnalysisTest
 5 {
 6 public static void main( String args[] )
 7 {
 8 Analysis application = new Analysis(); // create Analysis object
 9 application.processExamResults(); // call method to process results
10 } // end main
11
12 } // end class AnalysisTest
 
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
Raise Tuition
 
 
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): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
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
Passed: 6
Failed: 4
 

Lines 1316 of Fig. 4.12 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 is assigned 0 and studentCounter is assigned 1). Looping programs may require initialization at the beginning of each repetitionsuch reinitialization would normally be performed by assignment statements rather than in declarations.

The while statement (lines 1933) loops 10 times. During each iteration, the loop inputs and processes one exam result. Notice that the if...else statement (lines 2629) 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 the number of failures. The if statement at lines 3940 determines whether more than eight students passed the exam and, if so, outputs the message "Raise Tuition".

Error-Prevention Tip 4.3

Initializing local variables when they are declared helps the programmer avoid any compilation errors that might arise from attempts to use uninitialized data. While Java does not require that local variable initializations be incorporated into declarations, it does require that local variables be initialized before their values are used in an expression.

 

AnalysisTest Class That Demonstrates Class Analysis

Class AnalysisTest (Fig. 4.13) creates an Analysis object (line 8) and invokes the object's processExamResults method (line 9) to process a set of exam results entered by the user. Figure 4.13 shows the input and output from two sample executions of the program. During the first sample execution, the condition at line 39 of method processExamResults in Fig. 4.12 is truemore than eight students passed the exam, so the program outputs a message indicating that the tuition should be raised.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover

show all menu





Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net