950 likes | 970 Views
Chapter 3 Control Statements. 选择是艰难的. 谁能控制自己的命运?. 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).
E N D
Chapter 3 Control Statements 选择是艰难的 谁能控制自己的命运? Liang,Introduction to Java Programming,revised by Dai-kaiyu
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). Objectives Liang,Introduction to Java Programming,revised by Dai-kaiyu
Algorithms • Algorithm • Series of actions in specific order • The actions executed • The order in which actions execute • Program control • Specifying the order in which actions execute • Control structures help specify this order Liang,Introduction to Java Programming,revised by Dai-kaiyu
Pseudocode • 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
Control Structures • Sequential execution • Program statements execute one after the other • Transfer of control • Three control statements can specify order of statements • Sequence structure (built in Java) • Selection structure • Repetition structure • Flowchart • Graphical representation of algorithm • Flowlines indicate order in which actions execute Liang,Introduction to Java Programming,revised by Dai-kaiyu
Flowlines Action Symbols add grade to total total = total + grade; add 1 to counter counter = counter + 1 ; Connector Symbols • Flowcharting Java’s sequence structure. Liang,Introduction to Java Programming,revised by Dai-kaiyu
Decision Symbol true grade >= 60 print “Passed” false • Flowcharting the single-selection if structure. Liang,Introduction to Java Programming,revised by Dai-kaiyu
Selection Statements • if Statements • switch Statements • Conditional Operators Liang,Introduction to Java Programming,revised by Dai-kaiyu
Simple if Statements if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + “ for the circle of radius " + radius + " is " + area); } if (booleanExpression) { statement(s); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
Note Liang,Introduction to Java Programming,revised by Dai-kaiyu
Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } • logic error. • This error often occurs when you use the next-line block style. Wrong Liang,Introduction to Java Programming,revised by Dai-kaiyu
The if...else Statement Can’t use 0,1 if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } What if there is no else statement, the difference Liang,Introduction to Java Programming,revised by Dai-kaiyu
if...else Example if (radius >= 0) { area = radius * 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
Multiple Alternative if Statements better Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
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
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
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
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
Note The else clause matches the most recent if clause in the same block. Liang,Introduction to Java Programming,revised by Dai-kaiyu
Note, cont. • 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
TIP Liang,Introduction to Java Programming,revised by Dai-kaiyu
CAUTION better if (even = true) statement; compare Liang,Introduction to Java Programming,revised by Dai-kaiyu
1 // Fig. 2.20: Comparison.java 2 // Compare integers using if structures, relational operators 3 // and equality operators. 4 5 // Java extension packages 6 import javax.swing.JOptionPane; 7 8 public class Comparison { 9 10 // main method begins execution of Java application 11 public static void main( String args[] ) 12 { 13 String firstNumber; // first string entered by user 14 String secondNumber; // second string entered by user 15 String result; // a string containing the output 16 int number1; // first number to compare 17 int number2; // second number to compare 18 19 // read first number from user as a string 20 firstNumber = 21 JOptionPane.showInputDialog( "Enter first integer:" ); 22 23 // read second number from user as a string 24 secondNumber = 25 JOptionPane.showInputDialog( "Enter second integer:" ); 26 27 // convert numbers from type String to type int 28 number1 = Integer.parseInt( firstNumber ); 29 number2 = Integer.parseInt( secondNumber ); 30 31 // initialize result to empty String 32 result = ""; 33 Can we omit this statement? Liang,Introduction to Java Programming,revised by Dai-kaiyu
Test for equality, create new string, assign to result. Notice use of JOptionPane.INFORMATION_MESSAGE 34 if ( number1 == number2 ) 35 result = number1 + " == " + number2; 36 37 if ( number1 != number2 ) 38 result = number1 + " != " + number2; 39 40 if ( number1 < number2 ) 41 result = result + "\n" + number1 + " < " + number2; 42 43 if ( number1 > number2 ) 44 result = result + "\n" + number1 + " > " + number2; 45 46 if ( number1 <= number2 ) 47 result = result + "\n" + number1 + " <= " + number2; 48 49 if ( number1 >= number2 ) 50 result = result + "\n" + number1 + " >= " + number2; 51 52 // Display results 53 JOptionPane.showMessageDialog( 54 null, result, "Comparison Results", 55 JOptionPane.INFORMATION_MESSAGE ); 56 57 System.exit( 0 ); // terminate application 58 59 } // end method main 60 61 } // end class Comparison Liang,Introduction to Java Programming,revised by Dai-kaiyu
lengthy statement split after comma, operator,…,indent • JOptionPane.showMessageDialog( • null, result, “Comparison Results W AS ”+ • “ASASA DA DSA DAS DAS “, • JOptionPane.INFORMATION_MESSAGE ); In main method, we always do not put such trivial statements. Liang,Introduction to Java Programming,revised by Dai-kaiyu
Program Output Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
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 { // Display wrong status } Computer may think none of the branch will excute. Thus cause errors • Common Error Not initializing before using a variable in method Compute TaxWithSelectionStatement Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
switch Statement Flow Chart Liang,Introduction to Java Programming,revised by Dai-kaiyu
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1, ..., and valueN 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 switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } Liang,Introduction to Java Programming,revised by Dai-kaiyu
The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } 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. 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
Switch 语句的落空 下面程序的输出结果是什么 TestSwitch.java 在switch语句中,你通常在每一种case情况后都应使用break语句,否则,第一个相等情况后面所有的语句都会被执行,这种情况叫做落空 TestSwitch1.java TestSwitch2.java TestSwitch3.java Liang,Introduction to Java Programming,revised by Dai-kaiyu
Conditional operator (?:) • Java’s only ternary operator-takes three operands(Ternary ;Binary ;Unary ) • Grammer Variable = booleanexpression ? expression1 : expression2 If (booleanexpression) variable = expression1; else variable = expression2; Liang,Introduction to Java Programming,revised by Dai-kaiyu
Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; (booleanExpression) ? expression1 : expression2 Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
Repetitions • while Loops • do-while Loops • for Loops • break and continue Liang,Introduction to Java Programming,revised by Dai-kaiyu
while Loop Flow Chart int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } while (loop-continuation-condition) { // loop-body; Statement(s); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
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
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
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
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
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
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
Trace while Loop, cont. (count < 2) is false since 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
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
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. TestWhile Liang,Introduction to Java Programming,revised by Dai-kaiyu
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 FloatNotPrecise.java Liang,Introduction to Java Programming,revised by Dai-kaiyu