Professional Documents
Culture Documents
Lecture 3-1 Control Statements
Lecture 3-1 Control Statements
OBJECT-ORIENTED PROGRAMMING
C O N T R O L S T A T E M E N T S , A R R AY S
ALGORITHMS
Algorithms
The actions to execute The order in which these actions execute
Program control
Specifies the order in which actions execute in a program
PSEUDOCODE
Pseudocode
An informal language similar to English Helps programmers develop algorithms Does not run on computers
CONTROL STRUCTURES
Sequential execution
Statements are normally executed one after the other in the order in which they are written
Transfer of control
Can be performed by the goto statement
Structured programming eliminated goto statements
Diamonds
Decision symbols
Merge symbols
6
ifelse statement
Double-selection statement
switch statement
Multiple-selection statement
dowhile statement
Performs the actions in its body one or more times
for statement
Performs the actions in its body zero or more times
10
11
IF SINGLE-SELECTION STATEMENT
if statements
Execute an action if the specified condition is true Can be represented by a decision symbol (diamond) in a UML activity diagram
Transition arrows out of a decision symbol have guard conditions
Workflow follows the transition arrow whose guard condition is true
12
13
Conditional Operator ( ? : )
Javas only ternary operator (takes three operands) ? : and its three operands form a conditional expression
Entire conditional expression evaluates to the second operand if the first operand is true Entire conditional expression evaluates to the third operand if the first operand is false
14
15
IF ELSE DOUBLE-SELECTION
16
Dangling-else problem
elses are always associated with the immediately preceding if unless otherwise specified by braces { }
Blocks
Braces { } associate statements into blocks
17
Empty statements
Represented by placing a semicolon ( ; ) where a statement would normally be Can be used as an if body
18
19
21
WHILE
22
2
3 4 5 6 7 8
While grade counter is less than or equal to ten Prompt the user to enter the next grade Input the next grade Add the grade into the total Add one to the grade counter
9
10 11 Set the class average to the total divided by ten Print the class average
24
OUTLINE
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 // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // constructor initializes courseName public GradeBook( String name ) { } // end constructor public class GradeBook { private String courseName; // name of course this GradeBook represents // Fig. 4.6: GradeBook.java // GradeBook class that solves class-average problem using // counter-controlled repetition. import java.util.Scanner; // program uses class Scanner
25
OUTLINE
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter int total; // sum of grades entered by user int gradeCounter; // number of the grade to be entered next int grade; // grade value entered by user int average; // average of grades // determine class average based on 10 grades entered by user public void determineClassAverage() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // 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
OUTLINE
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 } // end class GradeBook // display total and average of grades System.out.printf( "\nTotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); } // end method determineClassAverage // termination phase average = total / 10; // integer division yields integer result // processing phase while ( gradeCounter <= 10 ) // loop 10 times { System.out.print( "Enter grade: " ); // prompt grade = input.nextInt(); // input next grade total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter by 1 } // end while
Display results
27
29
OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 } // end class GradeBookTest Welcome to the grade book for CS101 Introduction to Java Programming! Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter grade: grade: grade: grade: grade: grade: grade: grade: grade: grade: 67 78 89 67 87 98 93 85 82 100 myGradeBook.displayMessage(); // display welcome message myGradeBook.determineClassAverage(); // find average of 10 grades } // end main public class GradeBookTest { public static void main( String args[] ) { // create GradeBook object myGradeBook and // pass course name to constructor GradeBook myGradeBook = new GradeBook( // Fig. 4.7: GradeBookTest.java // Create GradeBook object and invoke its determineClassAverage method.
30
32
34
ERROR-PREVENTION TIP
When performing division by an expression whose value could be zero, explicitly test for this possibility and handle it appropriately in your program (e.g., by printing an error message) rather than allow the error to occur
35
OUTLINE
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 // Fig. 4.9: GradeBook.java // GradeBook class that solves class-average program using // sentinel-controlled repetition. import java.util.Scanner; // program uses class Scanner public class GradeBook { private String courseName; // name of course this GradeBook represents // constructor initializes courseName public GradeBook( String name ) { courseName = name; // initializes courseName } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName
OUTLINE
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 // 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 // determine the average of an arbitrary number of grades public void determineClassAverage() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int total; // sum of grades int gradeCounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter // processing phase // prompt for input and read grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextInt();
Declare local int variables total, gradeCounter and grade and double variable average
39
OUTLINE
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 83 } // end class GradeBook // display total and average (with two digits of precision) System.out.printf( "\nTotal of the %d grades entered is %d\n", gradeCounter, total ); System.out.printf( "Class average is %.2f\n", average ); } // end if else // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method determineClassAverage // termination phase // if user entered at least one grade... if ( gradeCounter != 0 ) { // calculate average of all grades entered average = (double) total / gradeCounter; // prompt for input and read next grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextInt(); } // end while // loop until sentinel value read from user while ( grade != -1 ) { total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter
45
OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // process 10 students using counter-controlled loop while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result (1 = pass, 2 = fail): " ); result = input.nextInt(); // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result (obtains value from user) public class Analysis { public void processExamResults { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // Fig. 4.12: Analysis.java // Analysis of examination results. import java.util.Scanner; // class uses class Scanner
47
OUTLINE
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 } // end class Analysis // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end method processExamResults // termination phase; prepare and display results // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; } // end while // if...else nested in while if ( result == 1 ) passes = passes + 1; else // if result 1, // increment passes; // else result is not 1, so
Determine whether this student passed or failed and increment the appropriate variable
48
ERROR-PREVENTION TIP
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
OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 // Fig. 4.13: AnalysisTest.java // Test program for class Analysis.
public class AnalysisTest { public static void main( String args[] ) { Analysis application = new Analysis(); // create Analysis object application.processExamResults(); // call method to process results } // end main } // end class AnalysisTest = = = = = = = = = = pass, pass, pass, pass, pass, pass, pass, pass, pass, pass, 2 2 2 2 2 2 2 2 2 2 = = = = = = = = = = fail): fail): fail): fail): fail): fail): fail): fail): fail): fail): 1 2 1 1 1 1 1 1 1 1
Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Enter result (1 Passed: 9 Failed: 1 Raise Tuition Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Enter result Passed: 6 Failed: 4 (1 (1 (1 (1 (1 (1 (1 (1 (1 (1
50
result in variable c
51
54
OUTLINE
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 5 5 6 5 6 6 // Fig. 4.16: Increment.java // Prefix increment and postfix increment operators. public class Increment { public static void main( String args[] ) { int c; // demonstrate postfix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( c++ ); // print 5 then postincrement System.out.println( c ); // print 6 System.out.println(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c System.out.println( c ); // print 5 System.out.println( ++c ); // preincrement then print 6 System.out.println( c ); // print 6 } // end main } // end class Increment
56
Operators
++ ++ * + < == ?: = --/ <= != += + % > ( type )
Associativity
right to left right to left left to right left to right left to right left to right right to left %= right to left
Type
unary postfix unary prefix Multiplicative Additive Relational Equality Conditional assignment
>=
-=
*=
/=
58
PRIMITIVE TYPES
Java is a strongly typed language
All variables have a type
Primitive types in Java are portable across all platforms that support Java
59
67
OUTLINE
1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for repetition statement. 3 4 public class ForCounter 5 { 6 7 8 9 10 11 12 13 System.out.println(); // output a newline 14 } // end main Control-variable name is 15 } // end class ForCounter 1 2 3 4 5 6 7 8 9 10 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 );
68
75
Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0
for ( int i = 99; i >= 0; i -= 11 )
76
OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // 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 } // end main
78
79
OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 // display headers System.out.printf( "%s%20s\n", "Year", "Amount on deposit" ); public class Interest { { double amount; // amount on deposit at end of each year double principal = 1000.0; // initial amount before interest double rate = 0.05; // interest rate // Fig. 5.6: Interest.java // Compound-interest calculations with for.
81
OUTLINE
15 16 17 18 19 20 21 22 23 24 // display the year and the amount System.out.printf( "%4d%,20.2f\n", year, amount ); } // end for } // end main // 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 );
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
82
static method
ClassName.methodName( arguments)
83
85
OUTLINE
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 );
} while ( counter <= 10 ); // end do...while System.out.println(); // outputs a newline } // end main
DO...WHILE
87
88
89
OUTLINE
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.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 } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName
90
OUTLINE
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",
"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" );
91
OUTLINE
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() ) Loop condition uses method hasNext to { grade = input.nextInt(); // read grade determine whether there is more data to input 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 ) { (grade / 10 ) is // determine which grade was entered controlling expression switch ( grade / 10 ) { case 9: // grade was between 90 switch statement determines case 10: // and 100 which case label to execute, ++aCount; // increment aCount depending on controlling expression break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch
92
OUTLINE
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 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;
93
OUTLINE
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
94
95
98
99
100
Loop 10 times OUTLINE (break) Exit for statement when count equals 5
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[] ) { int count; // control variable also used after loop terminates 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
Program output
103
OUTLINE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 System.out.printf( "%d ", count ); } // end for public class ContinueTest { public static void main( String args[] ) {
Loop 10 times
for ( int count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, continue; // skip remaining code in loop
Program output
104
software engineering and achieving the bestperforming software. Often, one of these goals is achieved at the expense of the other. For all but the
105
107
FIG. 5.14
108
109
FIG. 5.15
expression1
false false true true
expression2
false true false true
expression1 || expression2
false true true true
110
111
occur.
For example, in the expression ( i != 0 ) && ( 10 / i == 2 ), the second condition must appear
112
113
ERROR-PREVENTION TIPS
For clarity, avoid expressions with side effects in conditions. The side effects may look clever, but they can make it harder to understand code and can lead to subtle logic errors.
114
115
FIG. 5.16
expression1
false false true true
expression2
false true false true
expression1 ^ expression2
false true true false
116
expression
false true
!expression
true false
117
OUTLINE
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 // 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 ) ); // 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 ) ); 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 ) ); // Fig. 5.18: LogicalOperators.java // Logical operators.
OUTLINE
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // create truth table for ! (logical negation) operator "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 inclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
erators. java
// 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 ) );
System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)", "!false", ( !false ), "!true", ( !true ) ); } // end main
119
OUTLINE
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
120
FIG. 5.19
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
-=
*=
/=
%=
121
Selection structure
if, ifelse and switch
Repetition structure
while, dowhile and for
122
FIG. 5.20
123
FIG. 5.21
124
FIG. 5.22
125
| REPEATEDLY APPLYING THE STACKING RULE (RULE 2) OF FIG. 5.21 TO THE SIMPLEST ACTIVITY DIAGRAM.
FIG. 5.23
126
| REPEATEDLY APPLYING THE NESTING RULE (RULE 3) OF FIG. 5.21 TO THE SIMPLEST ACTIVITY DIAGRAM.
FIG. 5.24
127
FIG. 5.25
128