Presentation is loading. Please wait.

Presentation is loading. Please wait.

 1992-2007 Pearson Education, Inc. All rights reserved. 1 4.9 Formulating Algorithms: Sentinel- Controlled Repetition Example: – 計算任意數目個學生的平均成績 Sentinel-controlled.

Similar presentations


Presentation on theme: " 1992-2007 Pearson Education, Inc. All rights reserved. 1 4.9 Formulating Algorithms: Sentinel- Controlled Repetition Example: – 計算任意數目個學生的平均成績 Sentinel-controlled."— Presentation transcript:

1  1992-2007 Pearson Education, Inc. All rights reserved. 1 4.9 Formulating Algorithms: Sentinel- Controlled Repetition Example: – 計算任意數目個學生的平均成績 Sentinel-controlled repetition – Also known as indefinite repetition ( 不定次數重覆 ) – Use a sentinel ( 哨兵 ) value (also known as a signal, dummy or flag value) A sentinel value cannot be a valid input value – 如分數不會是負數,所以 ‘ -1 ’ 可以當作成績的哨兵值, 這表示當使用者輸入 ‘ -1 ’ 就表示迴圈結束 Choosing a sentinel value that is also a legitimate data value is a logic error

2  1992-2007 Pearson Education, Inc. All rights reserved. 2 4.9 Formulating Algorithms: Sentinel- Controlled Repetition (Cont.) Developing algorithm with top-down, stepwise refinement ( 改進 ) – Top: a single statement that conveys the overall function of the program – First refinement: multiple statements using only the sequence structure (page 3)page 3 – Second refinement: commit to specific variables, use specific control structures (page 4)page 4 Each refinement, as well as the top itself, is a complete specification of the algorithm — only the level of detail varies ( 詳細程度不同 ).

3  1992-2007 Pearson Education, Inc. All rights reserved. 3 Software Engineering Observation 4.3 Many programs can be divided logically into three phases: an initialization phase Ex: Initializes the variables a processing phase that inputs data values and adjusts program variables (e.g., counters and totals) accordingly; Ex: Input, sum and count the quiz grades and a termination phase that calculates and outputs the final results. Ex: Calculate and print the average

4  1992-2007 Pearson Education, Inc. All rights reserved. 4 Fig. 4.8 | Class-average problem pseudocode algorithm with sentinel-controlled repetition. 1Initialize total to zero 2Initialize counter to zero 3 4Prompt the user to enter the first grade 5Input the first grade (possibly the sentinel) 6 7While the user has not yet entered the sentinel 8Add this grade into the running total 9Add one to the grade counter 10Prompt the user to enter the next grade 11Input the next grade (possibly the sentinel) 12 13If the counter is not equal to zero 14Set the average to the total divided by the counter 15Print the average 16else 17Print “ No grades were entered ” explicitly test for division by 0

5  1992-2007 Pearson Education, Inc. All rights reserved. 5 Software Engineering Observation 4.4, 4.5 Terminate the top-down, stepwise refinement process when you have specified the pseudocode algorithm in sufficient detail for you to convert the pseudocode to Java. Normally, implementing the Java program is then straightforward. Writing programs without pseudocodes can lead to serious errors and delays in large, complex projects.

6  1992-2007 Pearson Education, Inc. All rights reserved. 6 Outline GradeBook.java (1 of 3) Assign a value to instance variable courseName Declare method setCourseName Declare method getCourseName

7  1992-2007 Pearson Education, Inc. All rights reserved. 7 Outline GradeBook.java (2 of 3) Declare method displayMessage Declare method determineClassAverage Declare and initialize Scanner variable input Declare local int variables total, gradeCounter and grade and double variable average

8  1992-2007 Pearson Education, Inc. All rights reserved. 8 Outline GradeBook.java (3 of 3) while loop iterates as long as grade != the sentinel value, -1 Calculate average grade using (double) to perform explicit conversion Display average grade Display “No grades were entered” message In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value.

9  1992-2007 Pearson Education, Inc. All rights reserved. 9 Common Programming Error 4.7 Omitting the braces that delimit a block can lead to logic errors, such as infinite loops. To prevent this problem, some programmers enclose the body of every control statement in braces even if the body contains only a single statement. Ex: while (grade != -1) total = total + grade; gradeCounter = gradeCounter + 1; System.out.print(“Enter grade or -1 to quit: “); grade = input.nextInt( ); Infinite loop

10  1992-2007 Pearson Education, Inc. All rights reserved. 10 4.9 Formulating Algorithms: Sentinel- Controlled Repetition (Cont.) Unary cast ( 鑄造 ) operator – Creates a temporary copy of its operand with a different data type example: (double) will create a temporary floating-point copy of its operand – Explicit conversion – The cast operator can be used to convert between primitive numeric types, such as int and double, and between related reference types (Chapter 10, Polymorphism ( 多形 ) ). Promotion ( 升級 ) – Converting a value (e.g. int ) to another data type (e.g. double ) to perform a calculation – Implicit conversion – Ex: average = (double) total / gradeCounter; The precedence of cast operator is one level higher than ‘/’ and ‘*’.

11  1992-2007 Pearson Education, Inc. All rights reserved. 11 Outline GradeBook Test.java Create a new GradeBook object Pass the course’s name to the GradeBook constructor as a string Call GradeBook ’s determineClassAverage method

12  1992-2007 Pearson Education, Inc. All rights reserved. 12 課堂練習 -4 1. 請輸入未知筆數的數字,輸出其加總結果 ( 請通知使 用者當輸入值等於 -9999 表示輸入結束 ) 2. 警察追小偷,輸入小偷車速,警察車速由 0 開始, 警察車速每次加 25 ,小偷車速每次加 15 ,請輸出 警察車速 大於小偷車速 時,警察車速 與 小偷車速 各為多少。 課後練習: 請輸入 2 個整數,輸出其最大公因數

13  1992-2007 Pearson Education, Inc. All rights reserved. 13 4.10 Formulating Algorithms: Nested Control Statements Control statements can be nested ( 套疊、巢狀 ) within one another – Place one control statement inside the body of the other – Example: (page 151) A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, ten of the students who completed this course took the exam. The college wants to know how well its students did on the exam. You have been asked to write a program to summarize the results. You have been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or a 2 if the student failed.

14  1992-2007 Pearson Education, Inc. All rights reserved. 14 Top – Analyze exam results and decide whether tuition should be raised First Refinement – Initialize variables – Input the 10 exam results, and count passes and failures – Print a summary of the exam results and decide whether the tuition should be raised

15  1992-2007 Pearson Education, Inc. All rights reserved. 15 Fig. 4.11 | Pseudocode for examination-results problem. Nested Control

16  1992-2007 Pearson Education, Inc. All rights reserved. 16 Outline Analysis.java (1 of 2) Declare processExamResults ’ local variables while loop iterates as long as studentCounter <= 10 Initializing local variables when they are declared

17  1992-2007 Pearson Education, Inc. All rights reserved. 17 Outline Analysis.java (2 of 2) Determine whether this student passed or failed and increment the appropriate variable Determine whether more than eight students passed the exam

18  1992-2007 Pearson Education, Inc. All rights reserved. 18 Error-Prevention Tip 4.3 Initializing local variables when they are declared helps the programmer avoid any compilation errors that might arise from attempts to use uninitialized data. While Java does not require that local variable initializations be incorporated into declarations, it does require that local variables be initialized before their values are used in an expression.

19  1992-2007 Pearson Education, Inc. All rights reserved. 19 Outline AnalysisTest.java Create an Analysis object More than 8 students passed the exam

20  1992-2007 Pearson Education, Inc. All rights reserved. 20 課堂練習 -5 Ex-04-20: 請輸入 10 筆實數,輸出其中最大實 數 Ex-04-26: 請輸入 1 個整數 n ,輸出 (1) 一列 n 個 ‘ * ’ (2) 以 n 為邊的實心正方形 (3) 輸出以 n 為邊的空心正方形 課後練習: ex04-22: 請輸入 10 筆實數,輸出其中最大 的 2 個實數 ex-4-28: 請輸入 2 進位的數字 ( 如: 10101) ,輸出其 10 進位值

21  1992-2007 Pearson Education, Inc. All rights reserved. 21 4.11 Compound Assignment Operators Compound assignment operators – An assignment statement of the form: variable = variable operator expression ; where operator is +, -, *, / or % can be written as: variable operator = expression ; – example: c = c + 3; can be written as c += 3; This statement adds 3 to the value in variable c and stores the result in variable c

22  1992-2007 Pearson Education, Inc. All rights reserved. 22 Fig. 4.14 | Arithmetic compound assignment operators.

23  1992-2007 Pearson Education, Inc. All rights reserved. 23 4.12 Increment and Decrement Operators Unary increment and decrement operators – Unary increment operator ( ++ ) adds one to its operand – Unary decrement operator ( -- ) subtracts one from its operand – Prefix ( 置前 ) increment (and decrement) operator Changes the value of its operand, then uses the new value of the operand in the expression in which the operation appears – Postfix ( 置後 ) increment (and decrement) operator Uses the current value of its operand in the expression in which the operation appears, then changes the value of the operand – Unlike binary operators, the unary increment and decrement operators should be placed next to their operands, with no intervening spaces.

24  1992-2007 Pearson Education, Inc. All rights reserved. 24 Fig. 4.15 | Increment and decrement operators.

25  1992-2007 Pearson Education, Inc. All rights reserved. 25 Outline Increment.java Postincrementing the c variable Preincrementing the c variable

26  1992-2007 Pearson Education, Inc. All rights reserved. 26 Common Programming Error 4.9 Attempting to use the increment or decrement operator on an expression other than one to which a value can be assigned is a syntax error. For example, writing ++(x + 1) is a syntax error because (x + 1) is not a variable.

27  1992-2007 Pearson Education, Inc. All rights reserved. 27 Fig. 4.17 | Precedence and associativity of the operators discussed so far.

28  1992-2007 Pearson Education, Inc. All rights reserved. 28 4.13 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 – boolean (16 bits), char (16 bits), byte (8 bits), short (16 bits), int (32 bits), long (64 bits), float (32 bits), double (64 bits) – Appendix D 有各 primitive type 之值域 Unlike C and C++, the primitive types in Java are portable across all computer platforms that support Java. Primitive type instance variables are automatically assigned default values ( false for boolean, and 0 for all other primitive types) Reference-type instance variables are initialized to the value null

29  1992-2007 Pearson Education, Inc. All rights reserved. 29 課堂練習 6 練習: (1) 請輸入 1 個大於等於 2 的正整數 n , 輸出 n 是否為質數 (2) 請輸入 1 個大於等於 2 的正整數 n , 輸出 2 … n 是否為質數


Download ppt " 1992-2007 Pearson Education, Inc. All rights reserved. 1 4.9 Formulating Algorithms: Sentinel- Controlled Repetition Example: – 計算任意數目個學生的平均成績 Sentinel-controlled."

Similar presentations


Ads by Google