Chapter 3 Control Statements Liang Introduction to Java

  • Slides: 95
Download presentation
Chapter 3 Control Statements 选择是艰难的 谁能控制自己的命运? Liang, Introduction to Java Programming, revised by Dai-kaiyu

Chapter 3 Control Statements 选择是艰难的 谁能控制自己的命运? Liang, Introduction to Java Programming, revised by Dai-kaiyu 1

Objectives • To understand the flow of control in selection and loop statements (§

Objectives • To understand the flow of control in selection and loop statements (§ 3. 2 -3. 7). • To use Boolean expressions to control selection statements and loop statements (§ 3. 2 -3. 7). • To implement selection control using if and nested if statements (§ 3. 2). • To implement selection control using switch statements (§ 3. 2). • To write expressions using the conditional operator (§ 3. 2). • To use while, do-while, and for loop statements to control the repetition of statements (§ 3. 4). • To write nested loops (§ 3. 4). • To know the similarities and differences of three types of loops (§ 3. 5). • To implement program control with break and continue (§ 3. 6). Liang, Introduction to Java Programming, revised by Dai-kaiyu 2

Algorithms l Algorithm ¡ Series of actions in specific order The actions executed l

Algorithms l Algorithm ¡ Series of actions in specific order The actions executed l The order in which actions execute l l Program control ¡ Specifying l the order in which actions execute Control structures help specify this order Liang, Introduction to Java Programming, revised by Dai-kaiyu 3

Pseudocode l Pseudocode ¡ Informal language for developing algorithms ¡ Not executed on computers

Pseudocode l Pseudocode ¡ Informal language for developing algorithms ¡ Not executed on computers ¡ Helps developers “think out” algorithms ¡ Normally describes only executable statements if student’s grade is greater then or equal to 60 Print " Passed" if(grade>=60) System. out. println(“Passed"); Liang, Introduction to Java Programming, revised by Dai-kaiyu 4

Control Structures l Sequential execution ¡ l Program statements execute one after the other

Control Structures l Sequential execution ¡ l Program statements execute one after the other Transfer of control ¡ Three control statements can specify order of statements l l Sequence structure (built in Java) Selection structure Repetition structure Flowchart ¡ Graphical representation of algorithm l Flowlines indicate order in which actions execute Liang, Introduction to Java Programming, revised by Dai-kaiyu 5

Flowlines Action Symbols add grade to total add 1 to counter total = total

Flowlines Action Symbols add grade to total add 1 to counter total = total + grade; counter = counter + 1 ; Connector Symbols Flowcharting Java’s sequence structure. Liang, Introduction to Java Programming, revised by Dai-kaiyu 6

Decision Symbol grade >= 60 true print “Passed” false Flowcharting the single-selection if structure.

Decision Symbol grade >= 60 true print “Passed” false Flowcharting the single-selection if structure. Liang, Introduction to Java Programming, revised by Dai-kaiyu 7

Selection Statements Ø if Statements Ø switch Statements Ø Conditional Operators Liang, Introduction to

Selection Statements Ø if Statements Ø switch Statements Ø Conditional Operators Liang, Introduction to Java Programming, revised by Dai-kaiyu 8

Simple if Statements if (boolean. Expression) { statement(s); } if (radius >= 0) {

Simple if Statements if (boolean. Expression) { statement(s); } if (radius >= 0) { area = radius * PI; System. out. println("The area" + “ for the circle of radius " + radius + " is " + area); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 9

Note Liang, Introduction to Java Programming, revised by Dai-kaiyu 10

Note Liang, Introduction to Java Programming, revised by Dai-kaiyu 10

Caution Adding a semicolon at the end of an if clause is a common

Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); Wrong { area = radius*PI; System. out. println( "The area for the circle of radius " + radius + " is " + area); } ulogic error. u. This error often occurs when you use the next-line block style. Liang, Introduction to Java Programming, revised by Dai-kaiyu 11

The if. . . else Statement Can’t use 0, 1 if (boolean. Expression) {

The if. . . else Statement Can’t use 0, 1 if (boolean. Expression) { statement(s)-for-the-true-case; What if there is no else } statement, the difference else { statement(s)-for-the-false-case; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 12

if. . . else Example if (radius >= 0) { area = radius *

if. . . else Example if (radius >= 0) { area = radius * 3. 14159; System. out. println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System. out. println("Negative input"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 13

Multiple Alternative if Statements better Liang, Introduction to Java Programming, revised by Dai-kaiyu 14

Multiple Alternative if Statements better Liang, Introduction to Java Programming, revised by Dai-kaiyu 14

Trace if-else statement Suppose score is 70. 0 The condition is false if (score

Trace if-else statement Suppose score is 70. 0 The condition is false if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; Liang, Introduction to Java Programming, revised by Dai-kaiyu 15

Trace if-else statement Suppose score is 70. 0 The condition is false if (score

Trace if-else statement Suppose score is 70. 0 The condition is false if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; Liang, Introduction to Java Programming, revised by Dai-kaiyu 16

Trace if-else statement Suppose score is 70. 0 The condition is true if (score

Trace if-else statement Suppose score is 70. 0 The condition is true if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; Liang, Introduction to Java Programming, revised by Dai-kaiyu 17

Trace if-else statement Suppose score is 70. 0 grade is C if (score >=

Trace if-else statement Suppose score is 70. 0 grade is C if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; Liang, Introduction to Java Programming, revised by Dai-kaiyu 18

Trace if-else statement Suppose score is 70. 0 Exit the if statement if (score

Trace if-else statement Suppose score is 70. 0 Exit the if statement if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; Liang, Introduction to Java Programming, revised by Dai-kaiyu 19

Note The else clause matches the most recent if clause in the same block.

Note The else clause matches the most recent if clause in the same block. Liang, Introduction to Java Programming, revised by Dai-kaiyu 20

Note, cont. n. To force the else clause to match the first if clause:

Note, cont. n. To force the else clause to match the first if clause: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System. out. println("A"); } else System. out. println("B"); This statement prints B. Liang, Introduction to Java Programming, revised by Dai-kaiyu 21

TIP Liang, Introduction to Java Programming, revised by Dai-kaiyu 22

TIP Liang, Introduction to Java Programming, revised by Dai-kaiyu 22

CAUTION better if (even = true) statement; compare Liang, Introduction to Java Programming, revised

CAUTION better if (even = true) statement; compare Liang, Introduction to Java Programming, revised by Dai-kaiyu 23

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 29 30 31 32 33 // Fig. 2. 20: Comparison. java // Compare integers using if structures, relational operators // and equality operators. // Java extension packages import javax. swing. JOption. Pane; public class Comparison { // main method begins execution of Java application public static void main( String args[] ) { String first. Number; // first string entered by user String second. Number; // second string entered by user String result; // a string containing the output int number 1; // first number to compare int number 2; // second number to compare // read first number from user as a string first. Number = JOption. Pane. show. Input. Dialog( "Enter first integer: " ); // read second number from user as a string second. Number = JOption. Pane. show. Input. Dialog( "Enter second integer: " ); // convert numbers from type String to type int number 1 = Integer. parse. Int( first. Number ); number 2 = Integer. parse. Int( second. Number ); // initialize result to empty String result = ""; Can we omit this statement? Liang, Introduction to Java Programming, revised by Dai-kaiyu 24

34 35 36 37 38 39 40 41 42 43 44 45 46 47

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 if ( number 1 == number 2 ) result = number 1 + " == " + number 2; if ( number 1 != number 2 ) result = number 1 + " != " + number 2; Test for equality, create new string, assign to result. if ( number 1 < number 2 ) result = result + "n" + number 1 + " < " + number 2; if ( number 1 > number 2 ) result = result + "n" + number 1 + " > " + number 2; if ( number 1 <= number 2 ) result = result + "n" + number 1 + " <= " + number 2; if ( number 1 >= number 2 ) result = result + "n" + number 1 + " >= " + number 2; // Display results JOption. Pane. show. Message. Dialog( null, result, "Comparison Results", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // terminate application // end method main // end class Comparison Notice use of JOption. Pane. INFORMATION_MESSAGE Liang, Introduction to Java Programming, revised by Dai-kaiyu 25

lengthy statement split after comma, operator, …, indent l l JOption. Pane. show. Message.

lengthy statement split after comma, operator, …, indent l l JOption. Pane. show. Message. Dialog( null, result, “Comparison Results W  AS ”+ “ASASA DA DSA DAS “, JOption. Pane. INFORMATION_MESSAGE ); In main method, we always do not put such trivial statements. Liang, Introduction to Java Programming, revised by Dai-kaiyu 26

Program Output Liang, Introduction to Java Programming, revised by Dai-kaiyu 27

Program Output Liang, Introduction to Java Programming, revised by Dai-kaiyu 27

Example 3. 1 Computing Taxes The US federal personal income tax is calculated based

Example 3. 1 Computing Taxes The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3. 1. Liang, Introduction to Java Programming, revised by Dai-kaiyu 28

Example 3. 1 Computing Taxes, cont. if (status == 0) { // Compute tax

Example 3. 1 Computing Taxes, cont. if (status == 0) { // Compute tax for single filers } else if (status == 1) { // Compute tax for married file jointly } else if (status == 2) { // Compute tax for married file separately } else if (status == 3) { // Compute tax for head of household } else { Computer may think none of the branch // Display wrong status will excute. Thus cause errors } Common Error Not initializing before using a variable in method Liang, Introduction to Java Programming, revised by Dai-kaiyu Compute Tax. With. Selection. Statement 29

switch Statements switch (status) { case 0: compute taxes for single filers; break; case

switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System. out. println("Errors: invalid status"); System. exit(0); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 30

switch Statement Flow Chart Liang, Introduction to Java Programming, revised by Dai-kaiyu 31

switch Statement Flow Chart Liang, Introduction to Java Programming, revised by Dai-kaiyu 31

switch Statement Rules The switch-expression must yield a value of char, byte, short, or

switch Statement Rules The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value 1, . . . , and value. N must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switchexpression. Note that value 1, . . . , and value. N are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. switch (switch-expression) { case value 1: statement(s)1; break; case value 2: statement(s)2; break; … case value. N: statement(s)N; break; default: statement(s)-for-default; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 32

switch Statement Rules The keyword break is optional, but it should be used at

switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value 1: statement(s)1; break; case value 2: statement(s)2; break; … case value. N: statement(s)N; break; default: statement(s)-for-default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switchexpression. The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. Liang, Introduction to Java Programming, revised by Dai-kaiyu 33

Switch 语句的落空 下面程序的输出结果是什么 Test. Switch. java 在switch语句中,你通常在每一种case情况后都应使用break语句,否则, 第一个相等情况后面所有的语句都会被执行,这种情况叫做落空 Test. Switch 1. java Test. Switch

Switch 语句的落空 下面程序的输出结果是什么 Test. Switch. java 在switch语句中,你通常在每一种case情况后都应使用break语句,否则, 第一个相等情况后面所有的语句都会被执行,这种情况叫做落空 Test. Switch 1. java Test. Switch 2. java Test. Switch 3. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 34

Conditional operator (? : ) ¡ Java’s only ternary operator-takes three operands(Ternary ; Binary

Conditional operator (? : ) ¡ Java’s only ternary operator-takes three operands(Ternary ; Binary ; Unary ) ¡ Grammer Variable = booleanexpression ? expression 1 : expression 2 If (booleanexpression) variable = expression 1; else variable = expression 2; Liang, Introduction to Java Programming, revised by Dai-kaiyu 35

Conditional Operator if (x > 0) y=1 else y = -1; is equivalent to

Conditional Operator if (x > 0) y=1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; (boolean. Expression) ? expression 1 : expression 2 Liang, Introduction to Java Programming, revised by Dai-kaiyu 36

Conditional Operator if (num % 2 == 0) System. out. println(num + “is even”);

Conditional Operator if (num % 2 == 0) System. out. println(num + “is even”); else System. out. println(num + “is odd”); System. out. println( (num % 2 == 0)? num + “is even” : num + “is odd”); Liang, Introduction to Java Programming, revised by Dai-kaiyu 37

Repetitions Øwhile Loops Ø do-while Loops Øfor Loops Ø break and continue Liang, Introduction

Repetitions Øwhile Loops Ø do-while Loops Øfor Loops Ø break and continue Liang, Introduction to Java Programming, revised by Dai-kaiyu 38

while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); } int count =

while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); } int count = 0; while (count < 100) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 39

Trace while Loop Initialize count int count = 0; while (count < 2) {

Trace while Loop Initialize count int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 40

Trace while Loop, cont. (count < 2) is true int count = 0; while

Trace while Loop, cont. (count < 2) is true int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 41

Trace while Loop, cont. Print Welcome to Java int count = 0; while (count

Trace while Loop, cont. Print Welcome to Java int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 42

Trace while Loop, cont. Increase count by 1 count is 1 now int count

Trace while Loop, cont. Increase count by 1 count is 1 now int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 43

Trace while Loop, cont. (count < 2) is still true since count is 1

Trace while Loop, cont. (count < 2) is still true since count is 1 int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 44

Trace while Loop, cont. Print Welcome to Java int count = 0; while (count

Trace while Loop, cont. Print Welcome to Java int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 45

Trace while Loop, cont. Increase count by 1 count is 2 now int count

Trace while Loop, cont. Increase count by 1 count is 2 now int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 46

Trace while Loop, cont. int count = 0; (count < 2) is false since

Trace while Loop, cont. int count = 0; (count < 2) is false since count is 2 now while (count < 2) { System. out. println("Welcome to Java!"); count++; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 47

Trace while Loop The loop exits. Execute the next statement after the loop. int

Trace while Loop The loop exits. Execute the next statement after the loop. int count = 0; while (count < 2) { System. out. println("Welcome to Java!"); count++; } Avoid infinite loops Liang, Introduction to Java Programming, revised by Dai-kaiyu 48

Example 3. 2: Using while Loops Problem: Write a program that reads and calculates

Example 3. 2: Using while Loops Problem: Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. Test. While Liang, Introduction to Java Programming, revised by Dai-kaiyu 49

Caution Don’t use floating-point values for equality checking in a loop control. // data

Caution Don’t use floating-point values for equality checking in a loop control. // data should be zero double data = Math. pow(Math. sqrt(2), 2) - 2; if (data == 0) System. out. println("data is zero"); else System. out. println("data is not zero"); Demo Float. Not. Precise. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 50

Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition) l Sentinel value ¡ Used to

Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition) l Sentinel value ¡ Used to indicated the end of data entry ¡ l Also called a signal value, flag value Average 2. java has indefinite repetition ¡ ¡ Indefinite repetition: the number of repetitions is not known before the loop begins executing. User enters sentinel value (-1) to end repetition Liang, Introduction to Java Programming, revised by Dai-kaiyu 51

Initialize variables Initialize total to zero Initialize counter to zero Input the first grade

Initialize variables Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) Input, sum up and count the quiz grades Calculate and print the class average While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Pseudocode algorithm that uses sentinelcontrolled repetition to solve the class-average problem. Determine the class average for the quiz Liang, Introduction to Java Programming, revised by Dai-kaiyu 52

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 29 30 31 32 // Fig. 4. 9: Average 2. java // Class average program with sentinel-controlled repetition. // Java core packages import java. text. Decimal. Format; Average 2. java // Java extension packages import javax. swing. JOption. Pane; public class Average 2 { // main method begins execution of Java application public static void main( String args[] ) { int grade. Counter, // number of grades entered grade. Value, // grade value total; // sum of grades double average; // average of all grades String input; // grade typed by user // Initialization phase total = 0; // clear total grade. Counter = 0; // prepare to loop // Processing phase // prompt for input and read grade from user input = JOption. Pane. show. Input. Dialog( "Enter Integer Grade, -1 to Quit: " ); // convert grade from a String to an integer grade. Value = Integer. parse. Int( input ); Liang, Introduction to Java Programming, revised by Dai-kaiyu 53

33 34 35 36 37 38 39 40 41 42 43 44 45 46

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 ); 59 60 61 62 63 64 65 66 while ( grade. Value != -1 ) { // add grade. Value to total loop until grade. Value total = total + grade. Value; equals sentinel value (-1) // add 1 to grade. Counter = grade. Counter + 1; // prompt for input and read grade from user input = JOption. Pane. show. Input. Dialog( "Enter Integer Grade, -1 to Quit: " ); Format numbers to nearest // convert grade from a String tohundredth an integer } grade. Value = Integer. parse. Int( input ); // Termination phase Decimal. Format two. Digits = new Decimal. Format( "0. 00" ); if ( grade. Counter != 0 ) { average = (double) total / grade. Counter; // display average of exam grades JOption. Pane. show. Message. Dialog( null, "Class average is " + two. Digits. format( average ), "Class Average", JOption. Pane. INFORMATION_MESSAGE Return a String } else JOption. Pane. show. Message. Dialog( null, "No grades were entered", "Class Average", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); // terminate application Liang, Introduction to Java Programming, revised by Dai-kaiyu 54

67 68 69 } } // end method main Average 2. java // end

67 68 69 } } // end method main Average 2. java // end class Average 2 Liang, Introduction to Java Programming, revised by Dai-kaiyu 55

double x=70. 89771; Decimal. Format y = new Decimal. Format("0. 000"); System. out. println(y.

double x=70. 89771; Decimal. Format y = new Decimal. Format("0. 000"); System. out. println(y. format( x )); l New operator ¡ ¡ ¡ l Creates an object as the program executes by obtaining enough memory to store an object of the type specified to the right of new Dynamic memory allocation operator Object of Class String is instantiated automatically Decimal. Format objects format number Liang, Introduction to Java Programming, revised by Dai-kaiyu 56

average = (double) total / grade. Counter; l Explicit conversion The value stored in

average = (double) total / grade. Counter; l Explicit conversion The value stored in total is still an integer ¡ Temporary double version of total created ¡ Promotion(implicit conversion) l Cast operators l Parentheses around the name of a data type l Float-points number are not always 100% precise l Liang, Introduction to Java Programming, revised by Dai-kaiyu 57

do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); Liang, Introduction to

do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); Liang, Introduction to Java Programming, revised by Dai-kaiyu 58

for Loops Components of a typical for structure header. Liang, Introduction to Java Programming,

for Loops Components of a typical for structure header. Liang, Introduction to Java Programming, revised by Dai-kaiyu 59

Can be any statement for (initial-action; loopcontinuation-condition; action-after-each-iteration) { // loop body; Statement(s); }

Can be any statement for (initial-action; loopcontinuation-condition; action-after-each-iteration) { // loop body; Statement(s); } for Loops int i; for (i = 0; i < 100; i++) { System. out. println( "Welcome to Java!"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 60

Trace for Loop int i; for (i = 0; i < 2; i++) {

Trace for Loop int i; for (i = 0; i < 2; i++) { System. out. println( "Welcome to Java!"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu Initialize count 61

Trace for Loop, cont. int i; for (i = 0; i < 2; i++)

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System. out. println( "Welcome to Java!"); } Execute initializer i is now 0 Liang, Introduction to Java Programming, revised by Dai-kaiyu 62

Trace for Loop, cont. int i; for (i = 0; i < 2; i++)

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System. out. println( "Welcome to Java!"); } (i < 2) is true since i is 0 Liang, Introduction to Java Programming, revised by Dai-kaiyu 63

Trace for Loop, cont. Print Welcome to Java int i; for (i = 0;

Trace for Loop, cont. Print Welcome to Java int i; for (i = 0; i < 2; i++) { System. out. println("Welcome to Java!"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 64

Trace for Loop, cont. Execute adjustment statement i now is 1 int i; for

Trace for Loop, cont. Execute adjustment statement i now is 1 int i; for (i = 0; i < 2; i++) { System. out. println("Welcome to Java!"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 65

Trace for Loop, cont. int i; for (i = 0; i < 2; i++)

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System. out. println("Welcome to Java!"); } (i < 2) is still true since i is 1 Liang, Introduction to Java Programming, revised by Dai-kaiyu 66

Trace for Loop, cont. Print Welcome to Java int i; for (i = 0;

Trace for Loop, cont. Print Welcome to Java int i; for (i = 0; i < 2; i++) { System. out. println("Welcome to Java!"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 67

Trace for Loop, cont. Execute adjustment statement i now is 2 int i; for

Trace for Loop, cont. Execute adjustment statement i now is 2 int i; for (i = 0; i < 2; i++) { System. out. println("Welcome to Java!"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu 68

Trace for Loop, cont. int i; for (i = 0; i < 2; i++)

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System. out. println("Welcome to Java!"); } (i < 2) is false since i is 2 Liang, Introduction to Java Programming, revised by Dai-kaiyu 69

Trace for Loop, cont. Exit the loop. Execute the next statement after the loop

Trace for Loop, cont. Exit the loop. Execute the next statement after the loop int i; for (i= 0; i < 2; i++) { System. out. println("Welcome to Java!"); } What if here is 2 Control variable’s scope: i can’t be used after the body of the structure, if variable i is defined inside the for structure Three parts of the for structure can be omitted, but the semicolon can’t Liang, Introduction to Java Programming, revised by Dai-kaiyu 70

Note n. The initial-action in a for loop can be a list of zero

Note n. The initial-action in a for loop can be a list of zero or more comma-separated expressions. for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something } n. The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. for (int i = 1; i < 100; System. out. println(i++)); Liang, Introduction to Java Programming, revised by Dai-kaiyu 71

Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true.

Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. (b) Is recommended to avoid confusion Liang, Introduction to Java Programming, revised by Dai-kaiyu 72

Example 3. 3 Using for Loops Problem: Write a program that sums a series

Example 3. 3 Using for Loops Problem: Write a program that sums a series that starts with 0. 01 and ends with 1. 0. The numbers in the series will increment by 0. 01, as follows: 0. 01 + 0. 02 + 0. 03 and so on. Test. Sum Liang, Introduction to Java Programming, revised by Dai-kaiyu 73

Example 3. 4 Displaying the Multiplication Table Problem: Write a program that uses nested

Example 3. 4 Displaying the Multiplication Table Problem: Write a program that uses nested for loops to print a multiplication table. Test. Multiplication. Table Liang, Introduction to Java Programming, revised by Dai-kaiyu 74

Which Loop to Use? The three forms of loop statements, while, do-while, and for,

Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. Liang, Introduction to Java Programming, revised by Dai-kaiyu 75

Recommendations Øuse the one that is most intuitive and comfortable for you. ØIn general,

Recommendations Øuse the one that is most intuitive and comfortable for you. ØIn general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. Ø A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. ØA do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition. Liang, Introduction to Java Programming, revised by Dai-kaiyu 76

Caution Adding a semicolon at the end of the for clause before the loop

Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++); { System. out. println("i is " + i); } Logic Error Liang, Introduction to Java Programming, revised by Dai-kaiyu 77

Caution, cont. Similarly, the following loop is also wrong: int i=0; Logic Error while

Caution, cont. Similarly, the following loop is also wrong: int i=0; Logic Error while (i < 10); { System. out. println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System. out. println("i is " + i); i++; Correct } while (i<10); Liang, Introduction to Java Programming, revised by Dai-kaiyu 78

Statements break and continue l break/continue ¡ l break statement ¡ l Alter flow

Statements break and continue l break/continue ¡ l break statement ¡ l Alter flow of control Causes immediate exit from control structure l Used in while, for, do/while or switch statements continue statement ¡ ¡ Skips remaining statements in loop body Proceeds to next iteration l Used in while, for or do/while statements Liang, Introduction to Java Programming, revised by Dai-kaiyu 79

Using the Keywords break and continue Liang, Introduction to Java Programming, revised by Dai-kaiyu

Using the Keywords break and continue Liang, Introduction to Java Programming, revised by Dai-kaiyu 80

The continue Keyword Liang, Introduction to Java Programming, revised by Dai-kaiyu 81

The continue Keyword Liang, Introduction to Java Programming, revised by Dai-kaiyu 81

Using break and continue Examples for using the break and continue keywords: F Example

Using break and continue Examples for using the break and continue keywords: F Example 3. 5: Test. Break. java Test. Break F Example 3. 6: Test. Continue. java Test. Continue Liang, Introduction to Java Programming, revised by Dai-kaiyu 82

Labeled break and continue Statements Every statement in Java can have an optional label

Labeled break and continue Statements Every statement in Java can have an optional label l Labeled block l ¡ ¡ l Labeled break statement ¡ ¡ l Set of statements enclosed by {} Preceded by a label Exit from nested control structures Proceeds to end of specified labeled block Labeled continue statement ¡ ¡ Skips remaining statements in nested-loop body Proceeds to beginning of specified labeled block Liang, Introduction to Java Programming, revised by Dai-kaiyu 83

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 29 30 31 32 33 34 35 // Fig. 5. 13: Break. Label. Test. java // Using the break statement with a label // Java extension packages import javax. swing. JOption. Pane; stop is the labeled block public class Break. Label. Test { // main method begins execution of Java application public static void main( String args[] ) { String output = ""; Loop 10 times stop: { // labeled block Nested loop 5 times // count 10 rows for ( int row = 1; row <= 10; row++ ) { // count 5 columns for ( int column = 1; column <= 5 ; column++ ) { // if row is 5, jump to end of "stop" block if ( row == 5 ) break stop; // jump to end of stop block output += "* } // end inner for structure output += "n"; } "; Exit to line 37 (next slide) // end outer for structure // the following line is skipped output += "n. Loops terminated normally"; by Dai-kaiyu Liang, Introduction to Java Programming, revised 84

36 37 38 39 40 41 42 43 44 45 46 47 } //

36 37 38 39 40 41 42 43 44 45 46 47 } // end labeled block JOption. Pane. show. Message. Dialog( null, output, "Testing break with a label", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // terminate application // end method main // end class Break. Label. Test Liang, Introduction to Java Programming, revised by Dai-kaiyu 85

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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 29 30 31 32 33 // Fig. 5. 14: Continue. Label. Test. java // Using the continue statement with a label // Java extension packages import javax. swing. JOption. Pane; next. Row is the labeled block public class Continue. Label. Test { // main method begins execution of Java application public static void main( String args[] ) { Loop 5 times String output = ""; next. Row: // target label of continue statement // count 5 rows for ( int row = 1; row <= 5; row++ Nested loop 10 times ) { output += "n"; // count 10 columns per row for ( int column = 1; column <= 10; column++ ) { // if column greater than row, start next row if ( column > row ) continue next. Row; // next iteration of // labeled loop output += "* } } "; // end inner for structure // end outer for structure continue to line 14 (next. Row) Liang, Introduction to Java Programming, revised by Dai-kaiyu 86

34 35 36 37 38 39 40 41 42 JOption. Pane. show. Message. Dialog(

34 35 36 37 38 39 40 41 42 JOption. Pane. show. Message. Dialog( null, output, "Testing continue with a label", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } // terminate application // end method main // end class Continue. Label. Test Liang, Introduction to Java Programming, revised by Dai-kaiyu 87

Example 3. 7 Finding the Greatest Common Divisor Problem: Write a program that prompts

Example 3. 7 Finding the Greatest Common Divisor Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Greatest. Common. Divisor Liang, Introduction to Java Programming, revised by Dai-kaiyu Run 88

Example 3. 8 Finding the Sales Amount Problem: You have just started a sales

Example 3. 8 Finding the Sales Amount Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5, 000. The scheme shown below is used to determine the commission rate. Sales Amount Commission Rate $0. 01–$5, 000 8 percent $5, 000. 01–$10, 000 10 percent $10, 000. 01 and above 12 percent Your goal is to earn $30, 000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $25, 000. Find. Sales. Amount Run Liang, Introduction to Java Programming, revised by Dai-kaiyu 89

Example 3. 9 Displaying a Pyramid of Numbers Problem: Write a program that prompts

Example 3. 9 Displaying a Pyramid of Numbers Problem: Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid. For example, if the input integer Three is 12, the output is shown below. parts (number. Of. Lines-row)*3 Print. Pyramid Liang, Introduction to Java Programming, revised by Dai-kaiyu Run 90

Example 3. 10 Displaying Prime Numbers Problem: Write a program that displays the first

Example 3. 10 Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: • For number = 2, 3, 4, 5, 6, . . . , test whether the number is prime. • Determine whether a given number is prime. • Count the prime numbers. • Print each prime number, and print 10 numbers per line. Prime. Number Liang, Introduction to Java Programming, revised by Dai-kaiyu Run 91

QUIZ Identify and correct the errors in each of the following. a. b. c.

QUIZ Identify and correct the errors in each of the following. a. b. c. d. e. if ( age >= 65 ); System. out. println( "Age greater than or equal to 65" ); else System. out. println( "Age is less than 65 )"; b. int x = 1, total; while ( x <= 10 ) { f. total += x; ++x; g. } h. While ( x <= 100 ) i. total += x; ++x; b. while ( y > 0 ) { System. out. println( y ); ++y; Liang, Introduction to Java Programming, revised by Dai-kaiyu 92

Answer a. b. c. d. e. a. Semicolon at the end of the if

Answer a. b. c. d. e. a. Semicolon at the end of the if condition should be removed. The closing double quote of the second System. out. println should be inside of the closing parenthesis. if ( age >= 65 ); System. out. println( "Age greater than or equal to 65" ); else System. out. println( "Age is less than 65 )"; b. int x = 1, total; while ( x <= 10 ) { b. The variable total should be initialized to zero. f. total += x; ++x; g. } h. c. While ( x <= 100 )c. The W in While should be lowercase. The two statements should be enclosed in curly i. total += x; braces to properly group them into the body ++x; of the while; otherwise the loop will be an d. int y = 5; infinite loop while ( y > 0 ) { System. out. println( y ); d. The ++ operator should be changed to --. The ++y; 93 Liang, Introduction to Java Programming, revised by Dai-kaiyu closing curly brace for the while loop is missing.

Find the error in each of the following. [Note: There may be more than

Find the error in each of the following. [Note: There may be more than one error. ] a. For ( x = 100, x >= 1, x++ ) System. out. println( x ); b. The following code should print whether integer value is odd or even: switch ( value % 2 ) { case 0: System. out. println( "Even integer" ); case 1: System. out. println( "Odd integer" ); } c. The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 ) System. out. println( x ); d. The following code should output the even integers from 2 to 100: counter = 2; do { System. out. println( counter ); counter += 2; Liang, Introduction to Java Programming, revised by Dai-kaiyu } While ( counter < 100 ); 94

Find the error in each of the following. [Note: There may be more than

Find the error in each of the following. [Note: There may be more than one error. ] a. For ( x = 100, x >= 1, x++ ) The F in for should be lowercase. Semicolons should be used System. out. println( x ); in the for header instead of commas. ++ should be -- b. The following code should print whether integer value is odd or even: switch ( value % 2 ) { case 0: System. out. println( "Even integer" ); case 1: System. out. println( "Odd integer" ); } A break statement should be placed in case 0 c. The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 ) += should be -= System. out. println( x ); d. The following code should output the even integers from 2 to 100: counter = 2; do { System. out. println( counter ); counter += 2; The W in While should be lowercase. < should be <= } While ( counter < 100 ); Liang, Introduction to Java Programming, revised by Dai-kaiyu 95