Download else

Document related concepts
no text concepts found
Transcript
Chapter 3 Control Statements
Prerequisites for Part I
Basic computer skills such as using Windows,
Internet Explorer, and Microsoft Word
Chapter 1 Introduction to Computers, Programs,
and Java
Chapter 2 Primitive Data Types and Operations
选择是艰难的
Chapter 3 Control Statements
谁能控制自己的命运?
Chapter 4 Methods
Chapter 5 Arrays
Liang,Introduction to Java Programming,revised by Dai-kaiyu
1
Objectives
• 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).
Liang,Introduction to Java Programming,revised by Dai-kaiyu
2
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
3
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
4
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
5
Flowlines
Action Symbols
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1 ;
Connector Symbols
Flowcharting Java’s sequence structure.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
6
Decision Symbol
grade >= 60
true
print “Passed”
false
Flowcharting the single-selection if structure.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
7
Selection Statements
 if Statements
 switch Statements
 Conditional Operators
Liang,Introduction to Java Programming,revised by Dai-kaiyu
8
Simple if Statements
if (booleanExpression) {
statement(s);
}
Boolean
Expression
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area" +
“ for the circle of radius "
+ radius + " is " + area);
}
false
false
(radius >= 0)
true
true
Statement(s)
(A)
area = radius * radius * PI;
System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);
(B)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
9
Note
Outer parentheses required
Braces can be omitted if the block contains a single
statement
if ((i > 0) && (i < 10)) {
System.out.println("i is an " +
+ "integer between 0 and 10");
}
Equivalent
if ((i > 0) && (i < 10))
System.out.println("i is an " +
+ "integer between 0 and 10");
(a)
(b)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
10
Caution
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0);
Wrong
{
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
11
The if...else Statement
Can’t use 0,1
if (booleanExpression) {
statement(s)-for-the-true-case;
What if there is no else
}
statement, the difference
else {
statement(s)-for-the-false-case;
}
true
Statement(s) for the true case
Boolean
Expression
false
Statement(s) for the false case
Liang,Introduction to Java Programming,revised by Dai-kaiyu
12
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
13
Multiple Alternative if Statements
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';
Equivalent
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';
better
Liang,Introduction to Java Programming,revised by Dai-kaiyu
14
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
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 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
17
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
18
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
19
Note
The else clause matches the most recent if clause in
the same block.
int i = 1;
int j = 2;
int k = 3;
int i = 1;
int j = 2;
int k = 3;
Equivalent
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
(a)
(b)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
20
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
21
TIP
if (number % 2 == 0)
even = true;
else
even = false;
Equivalent
boolean even
= number % 2 == 0;
(b)
(a)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
22
CAUTION
if (even == true)
System.out.println(
"It is even.");
if (even)
System.out.println(
"It is even.");
Equivalent
(b)
(a)
better
if (even = true)
statement;
compare
Liang,Introduction to Java Programming,revised by Dai-kaiyu
23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Fig. 2.20: Comparison.java
// Compare integers using if structures, relational operators
// and equality operators.
// Java extension packages
import javax.swing.JOptionPane;
public class Comparison {
// 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
// read first number from user as a string
firstNumber =
JOptionPane.showInputDialog( "Enter first integer:" );
// read second number from user as a string
secondNumber =
JOptionPane.showInputDialog( "Enter second integer:" );
// convert numbers from type String to type int
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// initialize result to empty String
result = "";
Can we omit this statement?
Liang,Introduction to Java Programming,revised by Dai-kaiyu
24
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
if ( number1 == number2 )
result = number1 + " == " + number2;
if ( number1 != number2 )
result = number1 + " != " + number2;
Test for equality, create new string,
assign to result.
if ( number1 < number2 )
result = result + "\n" + number1 + " < " + number2;
if ( number1 > number2 )
result = result + "\n" + number1 + " > " + number2;
if ( number1 <= number2 )
result = result + "\n" + number1 + " <= " + number2;
if ( number1 >= number2 )
result = result + "\n" + number1 + " >= " + number2;
// Display results
JOptionPane.showMessageDialog(
null, result, "Comparison Results",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// terminate application
// end method main
// end class Comparison
Notice use of
JOptionPane.INFORMATION_MESSAGE
Liang,Introduction to Java Programming,revised by Dai-kaiyu
25
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
26
Program Output
Liang,Introduction to Java Programming,revised by Dai-kaiyu
27
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
28
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 {
Computer may think none of the branch
// Display wrong status will excute. Thus cause errors
}
Common Error Not initializing before using a variable in method
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Compute TaxWithSelectionStatement
Run
29
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
30
switch Statement Flow Chart
status is 0
Compute tax for single filers
break
Compute tax for married file jointly
break
Compute tax for married file separatly
break
Compute tax for head of household
break
status is 1
status is 2
status is 3
default
Default actions
Next Statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu
31
switch Statement Rules
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 switchexpression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
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
32
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.
The default case, which is
optional, can be used to perform
actions when none of the
specified cases matches the
switch-expression.
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 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
33
Switch 语句的落空
下面程序的输出结果是什么
TestSwitch.java
在switch语句中,你通常在每一种case情况后都应使用break语句,否则,
第一个相等情况后面所有的语句都会被执行,这种情况叫做落空
TestSwitch1.java
TestSwitch2.java
TestSwitch3.java
Liang,Introduction to Java Programming,revised by Dai-kaiyu
34
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
35
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
36
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
37
Repetitions
while Loops
 do-while Loops
for Loops
 break and continue
Liang,Introduction to Java Programming,revised by Dai-kaiyu
38
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
Statement(s);
count++;
}
}
count = 0;
Loop
Continuation
Condition?
true
(count < 100)?
false
true
Statement(s)
(loop body)
(A)
false
System.out.println("Welcome to Java!");
count++;
(B)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
39
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
40
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
41
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
42
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
43
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
44
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
45
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
46
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
47
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
48
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
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu
49
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
50
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
51
Initialize variables
Initialize total to zero
Initialize counter to zero
Input the first grade (possibly the sentinel)
Input,sum up and count
the quiz grades
Calculate and print the
class average
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 sentinelcontrolled repetition to solve the class-average
problem.
Determine the class
average for the quiz
Liang,Introduction to Java Programming,revised by Dai-kaiyu
52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Fig. 4.9: Average2.java
// Class average program with sentinel-controlled repetition.
// Java core packages
import java.text.DecimalFormat;
Average2.java
// Java extension packages
import javax.swing.JOptionPane;
public class Average2 {
// 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
// Initialization phase
total = 0;
// clear total
gradeCounter = 0; // prepare to loop
// Processing phase
// prompt for input and read grade from user
input = JOptionPane.showInputDialog(
"Enter Integer Grade, -1 to Quit:" );
// convert grade from a String to an integer
gradeValue = Integer.parseInt( input );
Liang,Introduction to Java Programming,revised by Dai-kaiyu
53
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
while ( gradeValue != -1 ) {
// add gradeValue to total loop until gradeValue
total = total + gradeValue;equals sentinel value (-1)
// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
// prompt for input and read grade from user
input = JOptionPane.showInputDialog(
"Enter Integer Grade, -1 to Quit:" );
Format numbers to nearest
// convert grade from a String to hundredth
an integer
gradeValue = Integer.parseInt( input );
}
// Termination phase
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
if ( gradeCounter != 0 ) {
average = (double) total / gradeCounter;
// display average of exam grades
JOptionPane.showMessageDialog( null,
"Class average is " + twoDigits.format( average ),
"Class Average", JOptionPane.INFORMATION_MESSAGE );
Return a String
}
else
JOptionPane.showMessageDialog( null,
"No grades were entered", "Class Average",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
Liang,Introduction to Java Programming,revised by Dai-kaiyu
54
67
68
69
}
}
// end method main
Average2.java
// end class Average2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
55
double x=70.89771;
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu
56
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
57
do-while Loop
Statement(s)
(loop body)
true
do {
Loop
Continuation
Condition?
// Loop body;
false
Statement(s);
} while (loop-continuation-condition);
Liang,Introduction to Java Programming,revised by Dai-kaiyu
58
for Loops
Components of a typical for structure header.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
59
Can be any statement
for (initial-action; loopcontinuation-condition;
action-after-each-iteration)
{
// loop body;
Statement(s);
}
Intial-Action
Loop
Continuation
Condition?
for Loops
int i;
for (i = 0; i < 100; i++) {
System.out.println(
"Welcome to Java!");
}
i=0
false
(i < 100)?
true
Statement(s)
(loop body)
true
System.out.println(
"Welcome to Java");
Action-After-Each-Iteration
i++
Liang,Introduction to Java Programming,revised by Dai-kaiyu
(A)
(B)
false
60
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
61
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
Execute initializer
i is now 0
Liang,Introduction to Java Programming,revised by Dai-kaiyu
62
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
(i < 2) is true
since i is 0
63
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
64
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Execute adjustment statement
i now is 1
Liang,Introduction to Java Programming,revised by Dai-kaiyu
65
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
(i < 2) is still true
since i is 1
Liang,Introduction to Java Programming,revised by Dai-kaiyu
66
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
67
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Execute adjustment statement
i now is 2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
68
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
(i < 2) is false
since i is 2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
69
Trace for Loop, cont.
int i;
for (i= 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Exit the loop. Execute the next
statement after the loop
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
70
Note
The initial-action in a for loop can be a list of zero or
more comma-separated expressions.
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
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++));
Liang,Introduction to Java Programming,revised by Dai-kaiyu
71
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true.
(b) Is recommended to
avoid confusion
for ( ; ; ) {
// Do something
}
Equivalent
while (true) {
// Do something
}
(a)
(b)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
72
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: 0.01 + 0.02 + 0.03 and
so on.
TestSum
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
73
Example 3.4 Displaying the
Multiplication Table
Problem: Write a program that uses nested for loops to
print a multiplication table.
TestMultiplicationTable
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu
74
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.
while (loop-continuation-condition) {
// Loop body
}
Equivalent
for ( ; loop-continuation-condition; )
// Loop body
}
(A)
(B)
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(A)
(B)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
75
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
76
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
77
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
Logic Error
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.
int i=0;
do {
System.out.println("i is " + i);
i++;
Correct
} while (i<10);
Liang,Introduction to Java Programming,revised by Dai-kaiyu
78
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
79
Using the Keywords break and continue
Continuation
condition?
false
true
Statement(s)
break
Statement(s)
Next
Statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu
80
The continue Keyword
Continue
condition?
false
true
Statement(s)
continue
Statement(s)
Next
Statement
Liang,Introduction to Java Programming,revised by Dai-kaiyu
81
Using break and continue
Examples for using the break and continue
keywords:

Example 3.5: TestBreak.java
TestBreak

Run
Example 3.6: TestContinue.java
TestContinue
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
82
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
83
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 5.13: BreakLabelTest.java
// Using the break statement with a label
// Java extension packages
import javax.swing.JOptionPane; stop
is the labeled block
public class BreakLabelTest {
// main method begins execution of Java application
public static void main( String args[] )
{
String output = "";
Loop 10 times
stop: {
// labeled block
Nested
// count 10 rows
for ( int row = 1; row <= 10; row++ ) {
loop 5 times
// count 5 columns
for ( int column = 1; column <= 5 ; column++ ) {
// if row is 5, jump to end of "stop" block
if ( row == 5 )
break stop; // jump to end of stop block
output += "*
}
";
// end inner for structure
output += "\n";
}
Exit to line 37 (next slide)
// end outer for structure
// the following line is skipped
output += "\nLoops
terminated
normally";by Dai-kaiyu
Liang,Introduction
to Java Programming,revised
84
36
37
38
39
40
41
42
43
44
45
46
47
}
// end labeled block
JOptionPane.showMessageDialog(
null, output,"Testing break with a label",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// terminate application
// end method main
// end class BreakLabelTest
Liang,Introduction to Java Programming,revised by Dai-kaiyu
85
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Fig. 5.14: ContinueLabelTest.java
// Using the continue statement with a label
// Java extension packages
import javax.swing.JOptionPane;
nextRow is the labeled block
public class ContinueLabelTest {
// main method begins execution of Java application
public static void main( String args[] )
{
Loop 5 times
String output = "";
nextRow:
// target label of continue statement
// count 5 rows
for ( int row = 1; row <= 5; row++ Nested
) {
output += "\n";
loop 10 times
// count 10 columns per row
for ( int column = 1; column <= 10; column++ ) {
// if column greater than row, start next row
if ( column > row )
continue nextRow; // next iteration of
// labeled loop
output += "*
}
}
";
// end inner for structure
// end outer for structure
continue to line 14 (nextRow)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
86
34
35
36
37
38
39
40
41
42
JOptionPane.showMessageDialog(
null, output,"Testing continue with a label",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// terminate application
// end method main
// end class ContinueLabelTest
Liang,Introduction to Java Programming,revised by Dai-kaiyu
87
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.
GreatestCommonDivisor
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
88
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,000
8 percent
$5,000.01–$10,000
10 percent
$10,000.01 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
89
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
Three
is 12, the output is shown below.
parts
(numberOfLines-row)*3
PrintPyramid
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
90
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
91
QUIZ
Identify and correct the errors in each of the following.
a.
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;
}
a. While ( x <= 100 )
total += x;
++x;
b. while ( y > 0 ) {
System.out.println( y );
++y;
Liang,Introduction to Java Programming,revised by Dai-kaiyu
92
Answer
a.
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.
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 ) {
b. The variable total should be initialized to zero.
total += x;
++x;
}
c. The W in While should be lowercase. The two
c. While ( x <= 100 )
statements should be enclosed in curly
total += x;
braces to properly group them into the body
++x;
of the while; otherwise the loop will be an
d. int y = 5;
infinite loop
while ( y > 0 ) {
System.out.println( y );
d. The ++ operator should be changed to --. The
++y;
93
Liang,Introduction to Java Programming,revised by Dai-kaiyu
closing
curly brace for the while loop is missing.
Find the error in each of the following. [Note: There may be more than one error.]
a.For ( x = 100, x >= 1, x++ )
System.out.println( x );
b.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" );
}
c.The following code should output the odd integers from 19 to 1:
for ( x = 19; x >= 1; x += 2 )
System.out.println( x );
d.The following code should output the even integers from 2 to 100:
counter = 2;
do {
System.out.println( counter );
counter += 2;
Liang,Introduction
to Java Programming,revised by Dai-kaiyu
} While ( counter < 100
);
94
Find the error in each of the following. [Note: There may be more than one error.]
a.For ( x = 100, x >= 1, x++ )
The F in for should be lowercase. Semicolons should be used
System.out.println( x );
in the for header instead of commas. ++ should be --
b.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" );
}
A break statement should be placed in case 0
c.The following code should output the odd integers from 19 to 1:
for ( x = 19; x >= 1; x += 2 )
+= should be -=
System.out.println( x );
d.The following code should output the even integers from 2 to 100:
counter = 2;
do {
System.out.println( counter );
counter += 2;
The W in While should be lowercase. < should be <=
} While ( counter < 100
);
Liang,Introduction
to Java Programming,revised by Dai-kaiyu
95