4 9 Formulating Algorithms Sentinel Controlled Repetition Example

  • Slides: 29
Download presentation
4. 9 Formulating Algorithms: Sentinel. Controlled Repetition • Example: – 計算任意數目個學生的平均成績 • Sentinel-controlled repetition

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

4. 9 Formulating Algorithms: Sentinel. Controlled Repetition (Cont. ) • Developing algorithm with top-down,

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) – Second refinement: commit to specific variables, use specific control structures (page 4) • Each refinement, as well as the top itself, is a complete specification of the algorithm—only the level of detail varies (詳細程度不同). 2 1992 -2007 Pearson Education, Inc. All rights reserved.

3 Software Engineering Observation 4. 3 Many programs can be divided logically into three

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

4 1 2 Initialize total to zero Initialize counter to zero 3 4 Prompt

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

5 Software Engineering Observation 4. 4, 4. 5 Terminate the top-down, stepwise refinement process

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

Outline • Grade. Book. java (1 of 3) Assign a value to instance variable

Outline • Grade. Book. java (1 of 3) Assign a value to instance variable course. Name Declare method set. Course. Name Declare method get. Course. Name 6 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline Declare method display. Message • Grade. Book. java (2 of 3) Declare method

Outline Declare method display. Message • Grade. Book. java (2 of 3) Declare method determine. Class. Average Declare and initialize Scanner variable input Declare local int variables total, grade. Counter and grade and double variable average 7 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline while loop iterates as long as grade != the sentinel value, -1 •

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

9 Common Programming Error 4. 7 Omitting the braces that delimit a block can

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) Infinite loop total = total + grade; grade. Counter = grade. Counter + 1; System. out. print(“Enter grade or -1 to quit: “); grade = input. next. Int( ); 1992 -2007 Pearson Education, Inc. All rights reserved.

4. 9 Formulating Algorithms: Sentinel. Controlled Repetition (Cont. ) • Unary cast (鑄造) operator

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 / grade. Counter; 10 The precedence of cast operator is one level higher than ‘/’ and ‘*’. 1992 -2007 Pearson Education, Inc. All rights reserved.

Outline Create a new Grade. Book object • Grade. Book Test. java Pass the

Outline Create a new Grade. Book object • Grade. Book Test. java Pass the course’s name to the Grade. Book constructor as a string Call Grade. Book’s determine. Class. Average method 11 1992 -2007 Pearson Education, Inc. All rights reserved.

4. 10 Formulating Algorithms: Nested Control Statements • Control statements can be nested (套疊、巢狀)

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

 • Top – Analyze exam results and decide whether tuition should be raised

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

15 Nested Control Fig. 4. 11 | Pseudocode for examination-results problem. 1992 -2007 Pearson

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

Outline Declare process. Exam. Results’ local variables • Analysis. java (1 of 2) Initializing

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

Outline Determine whether this student passed or failed and increment the appropriate variable •

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

18 Error-Prevention Tip 4. 3 Initializing local variables when they are declared helps the

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

Outline Create an Analysis object • Analysis. Test. java More than 8 students passed

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

4. 11 Compound Assignment Operators • Compound assignment operators – An assignment statement of

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

22 Fig. 4. 14 | Arithmetic compound assignment operators. 1992 -2007 Pearson Education, Inc.

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

4. 12 Increment and Decrement Operators • Unary increment and decrement operators – Unary

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

24 Fig. 4. 15 | Increment and decrement operators. 1992 -2007 Pearson Education, Inc.

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

Outline • Increment. java Postincrementing the c variable Preincrementing the c variable 25 1992

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

26 Common Programming Error 4. 9 Attempting to use the increment or decrement operator

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

27 Fig. 4. 17 | Precedence and associativity of the operators discussed so far.

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

4. 13 Primitive Types • Java is a strongly typed language – All variables

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