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:
- 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.
- Count the number of test results of each type.
- Display a summary of the test results indicating the number of students who passed and the number who failed.
- If more than eight students passed the exam, print the message "Raise tuition."
After reading the problem statement carefully, we make the following observations:
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.
|
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
|
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