Presentation is loading. Please wait.

Presentation is loading. Please wait.

 1992-2007 Pearson Education, Inc. All rights reserved. 1 5 5 Control Statements: Part 2.

Similar presentations


Presentation on theme: " 1992-2007 Pearson Education, Inc. All rights reserved. 1 5 5 Control Statements: Part 2."— Presentation transcript:

1  1992-2007 Pearson Education, Inc. All rights reserved. 1 5 5 Control Statements: Part 2

2  1992-2007 Pearson Education, Inc. All rights reserved. 2 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.

3  1992-2007 Pearson Education, Inc. All rights reserved. 3 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition 5.3 for Repetition Statement 5.4 Examples Using the for Statement 5.5 do…while Repetition Statement 5.6 switch Multiple-Selection Statement 5.7 break and continue Statements 5.8 Logical Operators 5.9 Structured Programming Summary 5.12 Wrap-Up

4  1992-2007 Pearson Education, Inc. All rights reserved. 4 5.1 Introduction Continue structured-programming discussion – Introduce Java ’ s remaining control structures for, do … while, switch

5  1992-2007 Pearson Education, Inc. All rights reserved. 5 5.2 Essentials of Counter-Controlled Repetition Counter-controlled repetition requires: – Control variable (loop counter) – Initial value of the control variable – Increment/decrement of control variable through each loop – Loop-continuation condition that tests for the final value of the control variable

6  1992-2007 Pearson Education, Inc. All rights reserved. 6 Outline WhileCounter.java Control-variable name is counter Control-variable initial value is 1 Condition tests for counter ’s final value Increment for counter

7  1992-2007 Pearson Education, Inc. All rights reserved. 7 Common Programming Error 5.1 and Error-Prevention Tip 5.1 Because floating-point values may be approximate, controlling loops with floating- point variables may result in imprecise counter values and inaccurate termination tests. Control counting loops with integers.

8  1992-2007 Pearson Education, Inc. All rights reserved. 8 Good Programming Practice 5.1 and Software Engineering Observation 5.1 Place blank lines ( 空白列 ) above and below repetition and selection control statements, and indent the statement bodies to enhance readability. “ Keep it simple ” remains good advice for most of the code you will write.

9  1992-2007 Pearson Education, Inc. All rights reserved. 9 5.3 for Repetition Statement Handles counter-controlled-repetition details

10  1992-2007 Pearson Education, Inc. All rights reserved. 10 Outline ForCounter.java Line 10 int counter = 1; Line 10 counter <= 10; Line 10 counter++; Control-variable name is counter Control-variable initial value is 1 Condition tests for counter ’s final value Increment for counter

11  1992-2007 Pearson Education, Inc. All rights reserved. 11 Common Programming Error 5.2 Good Programming Practice 5.2 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( 少走一次迴圈錯誤 ). Using the final value in the condition of a while or for statement and using the <= relational operator helps avoid off- by-one errors. For a loop that prints the values 1 to 10, the loop- continuation condition should be counter <= 10 rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is correct). Many programmers prefer so-called zero-based counting, in which to count 10 times, counter would be initialized to zero and the loop-continuation test would be counter < 10.

12  1992-2007 Pearson Education, Inc. All rights reserved. 12 5.3 for Repetition Statement (Cont.) for ( initialization; loopContinuationCondition; increment ) statement; can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; } 分號 (;) ,常有 人寫成逗號 (,)

13  1992-2007 Pearson Education, Inc. All rights reserved. 13 Common Programming Error 5.4, 5.5 When a for statement ’ s control variable is declared in the initialization section of the for ’ s header, using the control variable after the for ’ s body is a compilation error. Placing a semicolon immediately to the right of the right parenthesis of a for header makes that for ’ s body an empty statement. For example: for ( int counter = 1; counter <= 10;counter++ ) ; This is normally a logic error.

14  1992-2007 Pearson Education, Inc. All rights reserved. 14 Error-Prevention Tip 5.2, 5.3 Infinite loops occur when the loop-continuation condition in a repetition statement never becomes false. To prevent this situation in a counter-controlled loop, ensure that the control variable is incremented (or decremented) during each iteration of the loop. In a sentinel-controlled loop, ensure that the sentinel value is eventually input. Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle ( 難解的 ) errors.

15  1992-2007 Pearson Education, Inc. All rights reserved. 15 5.4 Examples Using the for Statement Varying control variable in for statement – Vary control variable from 1 to 100 in increments of 1 for ( int i = 1; i <= 100; i++ ) – Vary control variable from 100 to 1 in increments of –1 for ( int i = 100; i >= 1; i-- ) – Vary control variable from 7 to 77 in increments of 7 for ( int i = 7; i <= 77; i += 7 ) – Vary control variable from 20 to 2 in decrements of 2 for ( int i = 20; i >= 2; i -= 2 ) – Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20 for ( int i = 2; i <= 20; i += 3 ) – Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for ( int i = 99; i >= 0; i -= 11 )

16  1992-2007 Pearson Education, Inc. All rights reserved. 16 Common Programming Error 5.6 Not using the proper relational operator in the loop- continuation condition of a loop that counts downward (e.g., using i = 1 in a loop counting down to 1) is usually a logic error.

17  1992-2007 Pearson Education, Inc. All rights reserved. 17 Outline Sum.java Line 11 increment number by 2 each iteration

18  1992-2007 Pearson Education, Inc. All rights reserved. 18 5.4 Examples Using the for Statement (Cont.) Initialization and increment expression can be comma-separated lists of expressions – E.g., lines 11-12 of Fig. 5.5 can be rewritten as for ( int number = 2; number <= 20; total += number, number += 2 ) ; // empty statement Limit the size of control statement headers to a single line if possible

19  1992-2007 Pearson Education, Inc. All rights reserved. 19 Good Programming Practice 5.5 Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear either before the loop (if they execute only once, like initialization statements) or in the body of the loop (if they execute once per iteration of the loop, like increment or decrement statements).

20  1992-2007 Pearson Education, Inc. All rights reserved. 20 Outline Interest.java (1 of 2) Line 8 Line 13 Java treats literal values with decimal points as type double Second string is right justified and displayed with a field width of 20

21  1992-2007 Pearson Education, Inc. All rights reserved. 21 Outline Interest.java (2 of 2) Lines 16-23 Line 22 Program output Calculate amount with for statement Use the comma (, ) formatting flag to display the amount with a thousands separator

22  1992-2007 Pearson Education, Inc. All rights reserved. 22 5.4 Examples Using the for Statement (Cont.) Formatting output – Field width – Minus sign ( - ) formatting flag for left justification – Comma (, ) formatting flag to output numbers with grouping separators static method – ClassName.methodName( arguments) Example: Math.pow( 1.0 + rate, year ) 試試將 Figure 5.6 第 13, 20 列的格式改成靠左對齊

23  1992-2007 Pearson Education, Inc. All rights reserved. 23 Good Programming Practice 5.6 Performance Tip 5.2 Do not use variables of type double (or float ) to perform precise monetary calculations. The imprecision of floating-point numbers can cause errors that will result in incorrect monetary values. In the exercises (ex 5.17 in p. 234), we explore the use of integers to perform monetary calculations. ( 改成以分計算 ) [Note: The Java API provides class java.math.BigDecimal for performing calculations with arbitrary precision floating-point values.] In loops, avoid calculations for which the result never changes — such calculations should typically be placed before the loop. ( 如: Math.pow( 1.0 + rate, year ) )

24  1992-2007 Pearson Education, Inc. All rights reserved. 24 練習 Ex-05-03: 以 for 加總由 1 到 99 的奇數 以 pow 方法計算並列印出 2.5 3 的值 以 while 迴圈列印 1 到 20 ,每 5 個數字一列, 以 “ \t ” 對齊 以 for 迴圈列印 1 到 20 ,每 5 個數字一列, 以 “ \t ” 對齊

25  1992-2007 Pearson Education, Inc. All rights reserved. 25 練習 Ex-05-14: 以 雙層巢狀 for 迴圈畫出邊長為 10 的 4 種直角三角形 Ex-05-19: 利用 for 迴圈以下列公式計算 π 的 50 個近似值 Ex-05-20: 利用雙層巢狀 for 迴圈將 ex-05-14 的 4 個三角形以水平 方式排成一列 ( 如上面右圖 )

26  1992-2007 Pearson Education, Inc. All rights reserved. 26 5.5 do … while Repetition Statement do…while statement – Similar to while statement – Tests loop-continuation after performing body of loop i.e., loop body always executes at least once

27  1992-2007 Pearson Education, Inc. All rights reserved. 27 Outline DoWhileTest.java Line 8 Lines 10-14 Program output Declares and initializes control variable counter Variable counter ’s value is displayed before testing counter ’s final value Always include braces in a do...while statement, even if they are not necessary. This helps eliminate ambiguity between the while statement and a do...while statement containing only one statement.

28  1992-2007 Pearson Education, Inc. All rights reserved. 28 5.6 switch Multiple-Selection Statement switch statement – Used for multiple selections 語法上並未規定一定要有 break , 有沒有 break 意義不同,但實 務上一般都會有。

29  1992-2007 Pearson Education, Inc. All rights reserved. 29 Outline GradeBook.java (1 of 5) Lines 8-14

30  1992-2007 Pearson Education, Inc. All rights reserved. 30 Outline GradeBook.java (2 of 5) Lines 50-54 Display prompt

31  1992-2007 Pearson Education, Inc. All rights reserved. 31 Outline GradeBook.java (3 of 5) Line 57 Line 72 controlling expression Lines 72-94 Loop condition uses method hasNext to determine whether there is more data to input switch statement determines which case label to execute, depending on controlling expression ( grade / 10 ) is controlling expression Forgetting a break statement when one is needed in a switch is a logic error.

32  1992-2007 Pearson Education, Inc. All rights reserved. 32 Outline GradeBook.java (4 of 5) Line 91 default case default case for grade less than 60 Provide a default case in switch statements. Including a default case focuses you on the need to process exceptional conditions. Although each case and the default case in a switch can occur in any order, always place the default case last.

33  1992-2007 Pearson Education, Inc. All rights reserved. 33 Outline GradeBook.java (5 of 5)

34  1992-2007 Pearson Education, Inc. All rights reserved. 34 Outline GradeBookTest.java (1 of 2) Lines 13-15 Call GradeBook public methods to count grades

35  1992-2007 Pearson Education, Inc. All rights reserved. 35 Outline GradeBookTest.java (2 of 2) Program output

36  1992-2007 Pearson Education, Inc. All rights reserved. 36 5.6 switch Multiple-Selection Statement (Cont.) Expression in each case – Constant integral expression Combination of integer constants that evaluates to a constant integer value – Character constant can be used too E.g., ‘ A ’, ‘ 7 ’ or ‘ $ ’ represents the integer values of these ASCII characters ( 參考: Appendix B) – Constant variable Declared with keyword final


Download ppt " 1992-2007 Pearson Education, Inc. All rights reserved. 1 5 5 Control Statements: Part 2."

Similar presentations


Ads by Google