Loops
Loops
5
Control Statements: Part 2
2005 Pearson Education, Inc. All rights reserved.
Not everything that can be counted counts, and not every thing that counts can be counted.
Albert Einstein
Intelligence is the faculty of making artificial objects, especially tools to make tools.
Henri Bergson
Every advantage in the past is judged in the light of the final issue.
Demosthenes
2005 Pearson Education, Inc. All rights reserved.
OBJECTIVES
In this chapter you will learn: The essentials of counter-controlled repetition. To use the for and do while repetition statements to execute statements in a program repeatedly. To understand multiple selection using the switch selection statement. To use the break and continue program control statements to alter the flow of control. To use the logical operators to form complex conditional expressions in control statements.
2005 Pearson Education, Inc. All rights reserved.
5.7
5.8 5.9 5.10 5.11 5.12
Logical Operators Structured Programming Summary (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals (Optional) Software Engineering Case Study: Identifying Objects States and Activities Wrap-Up
5.1 Introduction
Continue structured-programming discussion
Introduce Javas remaining control structures
for, dowhile, switch
Loop-continuation condition that tests for the final value of the control variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Fig. 5.1: WhileCounter.java // Counter-controlled repetition with the while repetition statement. public class WhileCounter { public static void main( String args[] ) {
Outline
int counter = 1; // declare and initialize control variable while ( counter <= 10 ) // loop-continuation condition { System.out.printf( "%d } // end while System.out.println(); // output a newline } // end main ", counter ); ++counter; // increment control variable by 1
10
11
Keep it simple remains good advice for most of the code you will write.
12
1 2 3 4 5 6 7 8 9 10 11 12
// Fig. 5.2: ForCounter.java // Counter-controlled repetition with the for repetition statement. public class ForCounter { public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter );
13
Outline
ForCounter.java
Line 10 int counter = 1; Line 10 counter <= 10; Line 10 counter++;
13 System.out.println(); // output a newline 14 } // end main 15 } // end class ForCounter Control-variable name is counter 1 2 3 4 5 6 7 8 9 10 Control-variable initial value is 1
14
Using an incorrect relational operator or an incorrect final value of a loop counter in the loop-continuation condition of a repetition statement can cause an off-by-one error.
15
16
17
18
19
20
21
22
23
24
25
Fig. 5.4 | UML activity diagram for the for statement in Fig. 5.2.
26
Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0
for ( int i = 99; i >= 0; i -= 11 )
27
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Fig. 5.5: Sum.java // Summing integers with the for statement. public class Sum { public static void main( String args[] ) { int total = 0; // initialize total // total even integers from 2 through 20 for ( int number = 2; number <= 20; number += 2 ) total += number; System.out.printf( "Sum is %d\n", total ); // display results
28
Outline
Sum.java
Line 11
29
30
31
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Fig. 5.6: Interest.java // Compound-interest calculations with for. public class Interest { public static void main( String args[] { double amount; // amount on deposit at end of each year double principal = 1000.0; // initial amount before interest double rate = 0.05; // interest rate // display headers System.out.printf( "%s%20s\n", "Year", "Amount on deposit" );
32
Outline
Interest.java
(1 of 2)
Line 8 Line 13 Second string is right justified and displayed with a field width of 20
15 16 17 18 19 20 21 22 23 24
// calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year amount = principal * Math.pow( 1.0 + rate, year ); // display the year and the amount System.out.printf( "%4d%,20.2f\n", year, amount ); } // end for } // end main
33
Outline
Calculate amount with for statement
Interest.java
(2 of 2)
25 } // end class Interest Year 1 2 3 4 5 6 7 8 9 10 Amount on deposit 1,050.00 1,102.50 1,157.63 1,215.51 1,276.28 1,340.10 1,407.10 1,477.46 1,551.33 1,628.89
Use the comma (,) formatting flag to display the amount with a thousands separator Lines 16-23 Line 22
Program output
34
static method
ClassName.methodName( arguments)
35
36
37
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Fig. 5.7: DoWhileTest.java // do...while repetition statement. public class DoWhileTest { public static void main( String args[] ) { int counter = 1; // initialize counter do { System.out.printf( "%d ++counter; ", counter );
38
Outline
DoWhileTest.java
} while ( counter <= 10 ); // end do...while System.out.println(); // outputs a newline } // end main
Program output
39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Fig. 5.9: GradeBook.java // GradeBook class uses switch statement to count A, B, C, D and F grades. import java.util.Scanner; // program uses class Scanner public class GradeBook { private String courseName; // name of course this GradeBook represents private int total; // sum of grades private int gradeCounter; // number of grades entered private int aCount; // count of A grades private int bCount; // count of B grades private int cCount; // count of C grades private int dCount; // count of D grades private int fCount; // count of F grades // constructor initializes courseName; // int instance variables are initialized to 0 by default public GradeBook( String name ) { courseName = name; // initializes courseName total = 100; aCount = 0; int grade = 50; } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName
40
Outline
GradeBook.java
(1 of 5) Lines 8-14
21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
// method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // display a welcome message to the GradeBook user public void displayMessage() { // getCourseName gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getCourseName() ); } // end method displayMessage // input arbitrary number of grades from user public void inputGrades() { Scanner input = new Scanner( System.in ); int grade; // grade entered by user System.out.printf( "%s\n%s\n %s\n %s\n",
41
Outline
GradeBook.java
(2 of 5)
Lines 50-54
Display prompt
"Enter the integer grades in the range 0-100.", "Type the end-of-file indicator to terminate input:", "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter" );
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
// loop until user enters the end-of-file indicator while ( input.hasNext() ) { grade = input.nextInt(); // read grade total += grade; // add grade to total ++gradeCounter; // increment number of grades // call method to increment appropriate counter incrementLetterGradeCounter( grade ); } // end while } // end method inputGrades // add 1 to appropriate counter for specified grade public void incrementLetterGradeCounter( int numericGrade ) { // determine which grade was entered switch ( numericGrade / 10 ) { case 9: // grade was between 90 case 10: // and 100 ++aCount; // increment aCount break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch
42
Outline
GradeBook.java
case 7: // grade was between 70 and 79 ++cCount; // increment cCount break; // exit switch case 6: // grade was between 60 and 69 ++dCount; // increment dCount break; // exit switch default: // grade was less than 60 ++fCount; // increment fCount break; // optional; will exit switch anyway } // end switch } // end method incrementLetterGradeCounter // display a report based on the grades entered by user public void displayGradeReport() { System.out.println( "\nGrade Report:" ); // if user entered at least one grade... if ( gradeCounter != 0 ) { // calculate average of all grades entered double average = (double) total / gradeCounter;
43
Outline
GradeBook.java
(4 of 5)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
// output summary of results System.out.printf( "Total of the %d grades entered is %d\n", gradeCounter, total ); System.out.printf( "Class average is %.2f\n", average ); System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", "Number of students who received each grade:", "A: ", aCount, "B: ", bCount, "C: ", cCount, "D: ", dCount, } // end if else // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method displayGradeReport // display number of A grades // display number of B grades // display number of C grades // display number of D grades
44
Outline
GradeBook.java
(5 of 5)
45
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Fig. 5.10: GradeBookTest.java // Create GradeBook object, input grades and display grade report. public class GradeBookTest { public static void main( String args[] ) { // create GradeBook object myGradeBook and // pass course name to constructor GradeBook myGradeBook = new GradeBook( "CS101 Introduction to Java Programming" );
46
Outline
GradeBookTest.java
15 myGradeBook.displayGradeReport(); // display report based on grades 16 } // end main 17 } // end class GradeBookTest
Welcome to the grade book for CS101 Introduction to Java Programming! Enter the integer grades in the range 0-100. Type the end-of-file indicator to terminate input: On UNIX/Linux/Mac OS X type <ctrl> d then press Enter On Windows type <ctrl> z then press Enter 99 92 45 57 63 71 76 85 90 100 ^Z Grade Report: Total of the 10 grades entered is 778 Class average is 77.80 Number of students who received each grade: A: 4 B: 1 C: 2 D: 1 F: 2
47
Outline
GradeBookTest.java
(2 of 2)
Program output
48
Provide a default case in switch statements. Including a default case focuses you on the need to process exceptional conditions.
49
Fig. 5.11 | switch multiple-selection statement UML activity diagram with break statements.
50
Character constant
E.g., A, 7 or $
Constant variable
Declared with keyword final
51
break statement
Causes immediate exit from control structure
Used in while, for, dowhile or switch statements
continue statement
Skips remaining statements in loop body Proceeds to next iteration
Used in while, for or dowhile statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Fig. 5.12: BreakTest.java // break statement exiting a for statement. public class BreakTest { public static void main( String args[] ) Loop 10 times { int count; // control variable also used after Exit loop for terminates statement (break) for ( count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, break; // terminate loop System.out.printf( "%d ", count ); } // end for System.out.printf( "\nBroke out of loop at count = %d\n", count ); } // end main } // end class BreakTest
52
Outline
Program output
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Fig. 5.13: ContinueTest.java // continue statement terminating an iteration of a for statement. public class ContinueTest { public static void main( String args[] ) {
53
Outline
Loop 10 times
ContinueTest.java
Skip line and proceed to for ( int count = 1; count <= 10; count++ ) // loop 10 12 times { line 7 when count equals 5 if ( count == 5 ) // if count is 5, continue; // skip remaining code in loop
System.out.printf( "%d ", count ); } // end for
15 System.out.println( "\nUsed continue to skip printing 5" ); 16 } // end main 17 } // end class ContinueTest 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5
Program output
54
55
^
!
56
57
58
59
expression1
false false true true
expression2
false true false true
expression1 || expression2
false true true true
60
61
62
63
64
65
expression1
false false true true
expression2
false true false true
expression1 ^ expression2
false true true false
66
expression
false true
!expression
true false
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Fig. 5.18: LogicalOperators.java // Logical operators. public class LogicalOperators { public static void main( String args[] ) { // create truth table for && (conditional AND) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional AND (&&)", "false && false", ( false && false ), "false && true", ( false && true ), "true && false", ( true && false ), "true && true", ( true && true ) ); // create truth table for || (conditional OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional OR (||)", "false || false", ( false || false ), "false || true", ( false || true ), "true || false", ( true || false ), "true || true", ( true || true ) ); // create truth table for & (boolean logical AND) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical AND (&)", "false & false", ( false & false ), "false & true", ( false & true ), "true & false", ( true & false ), "true & true", ( true & true ) );
67
Outline
LogicalOperators. java
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// create truth table for | (boolean logical inclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical inclusive OR (|)", "false | false", ( false | false ), "false | true", ( false | true ), "true | false", ( true | false ), "true | true", ( true | true ) ); // create truth table for ^ (boolean logical exclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical exclusive OR (^)", "false ^ false", ( false ^ false ), "false ^ true", ( false ^ true ), "true ^ false", ( true ^ false ), "true ^ true", ( true ^ true ) ); // create truth table for ! (logical negation) operator System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)", "!false", ( !false ), "!true", ( !true ) ); } // end main
68
Outline
Boolean LogicalOperators. logical inclusive ORjava truth table (2 of 3) Lines 30-35 Boolean logical exclusive OR truth table Lines 38-43
Conditional AND (&&) false && false: false false && true: false true && false: false true && true: true Conditional OR (||) false || false: false false || true: true true || false: true true || true: true Boolean logical AND (&) false & false: false false & true: false true & false: false true & true: true Boolean logical inclusive OR (|) false | false: false false | true: true true | false: true true | true: true Boolean logical exclusive OR (^) false ^ false: false false ^ true: true true ^ false: true true ^ true: false Logical NOT (!) !false: true !true: false
69
Outline
LogicalOperators. java
(3 of 3) Program output
70
Operators
++ -++ (type) * / + < <= == != & ^ | && || ?: = += + % > >= !
Associativity Type
right to left right to left left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left unary postfix unary prefix multiplicative additive relational equality boolean logical AND boolean logical exclusive OR boolean logical inclusive OR conditional AND conditional OR conditional assignment
-=
*=
/=
%=