Download presentation
Presentation is loading. Please wait.
1
Chapter 3 Control Statements
选择是艰难的 谁能控制自己的命运? Liang,Introduction to Java Programming,revised by Dai-kaiyu
2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Objectives To understand the flow of control in selection and loop statements (§ ). To use Boolean expressions to control selection statements and loop statements (§ ). 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
3
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
4
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
5
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
6
Liang,Introduction to Java Programming,revised by Dai-kaiyu
add grade to total total = total + grade; add 1 to counter counter = counter + 1 ; Flowcharting Java’s sequence structure. Flowlines Action Symbols Connector Symbols Liang,Introduction to Java Programming,revised by Dai-kaiyu
7
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
8
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
9
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
10
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Note Liang,Introduction to Java Programming,revised by Dai-kaiyu
11
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
12
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
13
Liang,Introduction to Java Programming,revised by Dai-kaiyu
if...else Example if (radius >= 0) { area = radius * radius * ; 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
14
Multiple Alternative if Statements
better 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 >= 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 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
17
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
18
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
19
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
20
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
21
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
22
Liang,Introduction to Java Programming,revised by Dai-kaiyu
TIP Liang,Introduction to Java Programming,revised by Dai-kaiyu
23
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
24
Can we omit this statement?
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 // main method begins execution of Java application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user String result; // a string containing the output int number1; // first number to compare int number2; // second number to compare 18 // read first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer:" ); 22 // read second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer:" ); 26 // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); 30 // initialize result to empty String result = ""; 33 Can we omit this statement? Liang,Introduction to Java Programming,revised by Dai-kaiyu
25
Liang,Introduction to Java Programming,revised by Dai-kaiyu
if ( number1 == number2 ) result = number1 + " == " + number2; 36 if ( number1 != number2 ) result = number1 + " != " + number2; 39 if ( number1 < number2 ) result = result + "\n" + number1 + " < " + number2; 42 if ( number1 > number2 ) result = result + "\n" + number1 + " > " + number2; 45 if ( number1 <= number2 ) result = result + "\n" + number1 + " <= " + number2; 48 if ( number1 >= number2 ) result = result + "\n" + number1 + " >= " + number2; 51 // Display results JOptionPane.showMessageDialog( null, result, "Comparison Results", JOptionPane.INFORMATION_MESSAGE ); 56 System.exit( 0 ); // terminate application 58 } // end method main 60 61 } // end class Comparison Test for equality, create new string, assign to result. Notice use of JOptionPane.INFORMATION_MESSAGE Liang,Introduction to Java Programming,revised by Dai-kaiyu
26
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
27
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Program Output Liang,Introduction to Java Programming,revised by Dai-kaiyu
28
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
29
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
30
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; case 2: compute taxes for married file separately; case 3: compute taxes for head of household; default: System.out.println("Errors: invalid status"); System.exit(0); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
31
switch Statement Flow Chart
Liang,Introduction to Java Programming,revised by Dai-kaiyu
32
switch Statement Rules
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; … case valueN: statement(s)N; default: statement(s)-for-default; } 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. Liang,Introduction to Java Programming,revised by Dai-kaiyu
33
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 value1: statement(s)1; break; case value2: statement(s)2; … case valueN: statement(s)N; 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 switch-expression. 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
34
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
35
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
36
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
37
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
38
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
39
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
40
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
41
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
42
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
43
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
44
Trace while Loop, cont. int count = 0; while (count < 2) {
(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
45
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
46
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
47
Trace while Loop, cont. int count = 0; while (count < 2) {
(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
48
Trace while Loop int count = 0; while (count < 2) {
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
49
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
50
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
51
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition) Sentinel value Used to indicated the end of data entry Also called a signal value, flag value Average2.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
52
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) 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 sentinel-controlled repetition to solve the class-average problem. Determine the class average for the quiz Initialize variables Input,sum up and count the quiz grades Calculate and print the class average Liang,Introduction to Java Programming,revised by Dai-kaiyu
53
Liang,Introduction to Java Programming,revised by Dai-kaiyu
1 // Fig. 4.9: Average2.java 2 // Class average program with sentinel-controlled repetition. 3 4 // Java core packages 5 import java.text.DecimalFormat; 6 7 // Java extension packages 8 import javax.swing.JOptionPane; 9 10 public class Average2 { 11 // main method begins execution of Java application public static void main( String args[] ) { int gradeCounter, // number of grades entered gradeValue, // grade value total; // sum of grades double average; // average of all grades String input; // grade typed by user 20 // Initialization phase total = 0; // clear total gradeCounter = 0; // prepare to loop 24 // Processing phase // prompt for input and read grade from user input = JOptionPane.showInputDialog( "Enter Integer Grade, -1 to Quit:" ); 29 // convert grade from a String to an integer gradeValue = Integer.parseInt( input ); 32 Average2.java Liang,Introduction to Java Programming,revised by Dai-kaiyu
54
loop until gradeValue equals sentinel value (-1)
while ( gradeValue != -1 ) { 34 // add gradeValue to total total = total + gradeValue; 37 // add 1 to gradeCounter gradeCounter = gradeCounter + 1; 40 // prompt for input and read grade from user input = JOptionPane.showInputDialog( "Enter Integer Grade, -1 to Quit:" ); 44 // convert grade from a String to an integer gradeValue = Integer.parseInt( input ); } 48 // Termination phase DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 51 if ( gradeCounter != 0 ) { average = (double) total / gradeCounter; 54 // display average of exam grades JOptionPane.showMessageDialog( null, "Class average is " + twoDigits.format( average ), "Class Average", JOptionPane.INFORMATION_MESSAGE ); } else JOptionPane.showMessageDialog( null, "No grades were entered", "Class Average", JOptionPane.INFORMATION_MESSAGE ); 64 System.exit( 0 ); // terminate application 66 loop until gradeValue equals sentinel value (-1) Format numbers to nearest hundredth Return a String Liang,Introduction to Java Programming,revised by Dai-kaiyu
55
67 } // end method main 68 69 } // end class Average2
Average2.java Liang,Introduction to Java Programming,revised by Dai-kaiyu
56
Liang,Introduction to Java Programming,revised by Dai-kaiyu
double x= ; DecimalFormat y = new DecimalFormat("0.000"); System.out.println(y.format( x )); New operator 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 DecimalFormat objects format number 70.898 70.8970.890 Liang,Introduction to Java Programming,revised by Dai-kaiyu
57
Liang,Introduction to Java Programming,revised by Dai-kaiyu
average = (double) total / gradeCounter; Explicit conversion The value stored in total is still an integer Temporary double version of total created Promotion(implicit conversion) Cast operators Parentheses around the name of a data type Float-points number are not always 100% precise Liang,Introduction to Java Programming,revised by Dai-kaiyu
58
Liang,Introduction to Java Programming,revised by Dai-kaiyu
do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); Liang,Introduction to Java Programming,revised by Dai-kaiyu
59
Liang,Introduction to Java Programming,revised by Dai-kaiyu
for Loops Components of a typical for structure header. Liang,Introduction to Java Programming,revised by Dai-kaiyu
60
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Can be any statement for Loops for (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
61
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Trace for Loop Initialize count int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
62
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Trace for Loop, cont. Execute initializer i is now 0 int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
63
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Trace for Loop, cont. (i < 2) is true since i is 0 int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Liang,Introduction to Java Programming,revised by Dai-kaiyu
64
Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
65
Trace for Loop, cont. int i; for (i = 0; i < 2; i++) {
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
66
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Trace for Loop, cont. (i < 2) is still true since i 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
67
Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
68
Trace for Loop, cont. int i; for (i = 0; i < 2; i++) {
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
69
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Trace for Loop, cont. (i < 2) is false since i 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
70
Trace for Loop, cont. int i; for (i= 0; i < 2; i++) {
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
71
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. 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++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something } Liang,Introduction to Java Programming,revised by Dai-kaiyu
72
(b) Is recommended to avoid confusion
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
73
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: and so on. TestSum Liang,Introduction to Java Programming,revised by Dai-kaiyu
74
Example 3.4 Displaying the Multiplication Table
Problem: Write a program that uses nested for loops to print a multiplication table. TestMultiplicationTable Liang,Introduction to Java Programming,revised by Dai-kaiyu
75
Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
76
Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
77
Liang,Introduction to Java Programming,revised by Dai-kaiyu
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
78
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Caution, cont. Similarly, the following loop is also wrong: int i=0; 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. do { } while (i<10); Logic Error Correct Liang,Introduction to Java Programming,revised by Dai-kaiyu
79
Statements break and continue
break/continue Alter flow of control break statement Causes immediate exit from control structure Used in while, for, do/while or switch statements continue statement Skips remaining statements in loop body Proceeds to next iteration Used in while, for or do/while statements Liang,Introduction to Java Programming,revised by Dai-kaiyu
80
Using the Keywords break and continue
Liang,Introduction to Java Programming,revised by Dai-kaiyu
81
Liang,Introduction to Java Programming,revised by Dai-kaiyu
The continue Keyword Liang,Introduction to Java Programming,revised by Dai-kaiyu
82
Using break and continue
Examples for using the break and continue keywords: Example 3.5: TestBreak.java TestBreak Example 3.6: TestContinue.java TestContinue Liang,Introduction to Java Programming,revised by Dai-kaiyu
83
Labeled break and continue Statements
Every statement in Java can have an optional label Labeled block Set of statements enclosed by {} Preceded by a label Labeled break statement 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
84
stop is the labeled block
1 // Fig. 5.13: BreakLabelTest.java 2 // Using the break statement with a label 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class BreakLabelTest { 8 // main method begins execution of Java application public static void main( String args[] ) { String output = ""; 13 stop: { // labeled block 15 // count 10 rows for ( int row = 1; row <= 10; row++ ) { 18 // count 5 columns for ( int column = 1; column <= 5 ; column++ ) { 21 // if row is 5, jump to end of "stop" block if ( row == 5 ) break stop; // jump to end of stop block 25 output += "* "; 27 } // end inner for structure 29 output += "\n"; 31 } // end outer for structure 33 // the following line is skipped output += "\nLoops terminated normally"; stop is the labeled block Loop 10 times Nested loop 5 times Exit to line 37 (next slide) Liang,Introduction to Java Programming,revised by Dai-kaiyu
85
Liang,Introduction to Java Programming,revised by Dai-kaiyu
36 } // end labeled block 38 JOptionPane.showMessageDialog( null, output,"Testing break with a label", JOptionPane.INFORMATION_MESSAGE ); 42 System.exit( 0 ); // terminate application 44 } // end method main 46 47 } // end class BreakLabelTest Liang,Introduction to Java Programming,revised by Dai-kaiyu
86
nextRow is the labeled block
1 // Fig. 5.14: ContinueLabelTest.java 2 // Using the continue statement with a label 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class ContinueLabelTest { 8 // main method begins execution of Java application public static void main( String args[] ) { String output = ""; 13 nextRow: // target label of continue statement 15 // count 5 rows for ( int row = 1; row <= 5; row++ ) { output += "\n"; 19 // count 10 columns per row for ( int column = 1; column <= 10; column++ ) { 22 // if column greater than row, start next row if ( column > row ) continue nextRow; // next iteration of // labeled loop 27 output += "* "; 29 } // end inner for structure 31 } // end outer for structure 33 nextRow is the labeled block Loop 5 times Nested loop 10 times continue to line 14 (nextRow) Liang,Introduction to Java Programming,revised by Dai-kaiyu
87
Liang,Introduction to Java Programming,revised by Dai-kaiyu
JOptionPane.showMessageDialog( null, output,"Testing continue with a label", JOptionPane.INFORMATION_MESSAGE ); 37 System.exit( 0 ); // terminate application 39 } // end method main 41 42 } // end class ContinueLabelTest Liang,Introduction to Java Programming,revised by Dai-kaiyu
88
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. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisor Run Liang,Introduction to Java Programming,revised by Dai-kaiyu
89
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, percent $5,000.01–$10, percent $10, 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. FindSalesAmount Run Liang,Introduction to Java Programming,revised by Dai-kaiyu
90
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 is 12, the output is shown below. Three parts (numberOfLines-row)*3 PrintPyramid Run Liang,Introduction to Java Programming,revised by Dai-kaiyu
91
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. PrimeNumber Run Liang,Introduction to Java Programming,revised by Dai-kaiyu
92
Liang,Introduction to Java Programming,revised by Dai-kaiyu
QUIZ Identify and correct the errors in each of the following. 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 ) { total += x; ++x; } While ( x <= 100 ) total += x; ++x; while ( y > 0 ) { System.out.println( y ); ++y; Liang,Introduction to Java Programming,revised by Dai-kaiyu
93
Liang,Introduction to Java Programming,revised by Dai-kaiyu
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. Answer 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 ) { total += x; ++x; } c. While ( x <= 100 ) total += x; ++x; d. int y = 5; while ( y > 0 ) { System.out.println( y ); ++y; b. The variable total should be initialized to zero. c. The W in While should be lowercase. The two statements should be enclosed in curly braces to properly group them into the body of the while; otherwise the loop will be an infinite loop d. The ++ operator should be changed to --. The closing curly brace for the while loop is missing. Liang,Introduction to Java Programming,revised by Dai-kaiyu
94
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Find the error in each of the following. [Note: There may be more than one error.] For ( x = 100, x >= 1, x++ ) System.out.println( x ); 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" ); } The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 ) System.out.println( x ); The following code should output the even integers from 2 to 100: counter = 2; do { System.out.println( counter ); counter += 2; } While ( counter < 100 ); Liang,Introduction to Java Programming,revised by Dai-kaiyu
95
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Find the error in each of the following. [Note: There may be more than one error.] For ( x = 100, x >= 1, x++ ) System.out.println( x ); 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" ); } The following code should output the odd integers from 19 to 1: for ( x = 19; x >= 1; x += 2 ) System.out.println( x ); The following code should output the even integers from 2 to 100: counter = 2; do { System.out.println( counter ); counter += 2; } While ( counter < 100 ); The F in for should be lowercase. Semicolons should be used in the for header instead of commas. ++ should be -- A break statement should be placed in case 0 += should be -= The W in While should be lowercase. < should be <= Liang,Introduction to Java Programming,revised by Dai-kaiyu
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.