CMPS161 Class Notes Chap 03
CMPS161 Class Notes Chap 03
3.1 Introduction
In this chapter, you will learn various selection and loop control statements.
Java provides selection statements that let you choose actions with two or more
alternative courses.
Java provides a powerful control structure called a loop, which controls how many
times an operation or a sequence of operation is performed in succession.
if (booleanExpression) {
statement(s);
} // execution flow chart is shown in Figure (A)
Example
if (radius >= 0) {
area = radius*radius*PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
} // if the Boolean expression evaluates to T, the statements in the
block are executed as shown in figure (B)
false false
Boolean (radius >= 0)
Expression
true true
(A) (B)
Outer parentheses required Braces can be omitted if the block contains a single
statement
if ((i > 0) && (i < 10)) { if ((i > 0) && (i < 10))
Equivalent
System.out.println("i is an " + System.out.println("i is an " +
+ "integer between 0 and 10"); + "integer between 0 and 10");
}
(a) (b)
Caution:
o Adding a semicolon at the end of an if clause is a common mistake.
o This mistake is hard to find, because it is not a compilation error or a runtime
error, it is a logic error.
o This error often occurs when you use the next-line block style.
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
true false
Boolean
Expression
Statement(s) for the true case Statement(s) for the false case
FIGURE 3.2 An if … else executes statements for the true case if the Boolean expression
evaluations are true; otherwise, statements for the false case are executed.
if...else Example
if (radius >= 0) {
area = radius*radius*PI;
If radius >= 0 is true, area is computed and displayed; if it is false, the message
“Negative input” is printed.
Using the if … else statement, you can rewrite the following code for determining
whether a number is even or odd, as follows:
if (number % 2 == 0)
System.out.println(number + “ is even.”);
if (number % 2 != 0)
System.out.println(number + “is odd.”);
The statement in an if or if ... else statement can be any legal Java statement,
including another if or if ... else statement. The inner if statement is said to be nested
inside the outer if statement.
The inner if statement can contain another if statement.
There is no limit to the depth of the nesting.
if (i > k) {
if (j > k)
System.out.println(“i and j are greater than k”);
}
else
System.out.println(“i is less than or equal to k”);
// the if (j > k) is nested inside the if (i > k)
The nested if statement can be used to implement multiple alternatives.
Note:
The else clause matches the most recent unmatched if clause in the same block. For
example, the following statement:
is equivalent to:
Nothing is printed from the preceding statement because the compiler ignores
indentation. To force the else clause to match the first if clause, you must add a pair
of braces:
int i = 1; int j = 2; int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
Caution
To test whether a Boolean variable is true or false in a test condition, it is redundant
to use the equality comparison operator like this:
if (even == true)
System.out.println(“It is even.”);
if (even)
System.out.println(“It is even.”);
if (even = true)
System.out.println(“It is even.”);
This statement does not have syntax errors. It assigns true to even so that even is
always true.
This problem is taken from example 3.1 (Page 86). Write a program that prompts
the user to enter the filing status and taxable income and computes the tax for the year
2002.
import javax.swing.JOptionPane;
public class ComputeTaxWithSelectionStatement {
public static void main(String[] args) {
// Prompt the user to enter filing status
String statusString = JOptionPane.showInputDialog(null,
"Enter the filing status:\n" +
"(0-single filer, 1-married jointly,\n" +
"2-married separately, 3-head of household)",
"Example 3.1 Input", JOptionPane.QUESTION_MESSAGE);
int status = Integer.parseInt(statusString);
// Prompt the user to enter taxable income
String incomeString = JOptionPane.showInputDialog(null,
"Enter the taxable income:",
"Example 3.1 Input", JOptionPane.QUESTION_MESSAGE);
double income = Double.parseDouble(incomeString);
// Compute tax
double tax = 0;
if (status == 0) { // Compute tax for single filers
if (income <= 6000)
tax = income * 0.10;
else if (income <= 27950)
tax = 6000 * 0.10 + (income - 6000) * 0.15;
else if (income <= 67700)
tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +
(income - 27950) * 0.27;
else if (income <= 141250)
tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +
(67700 - 27950) * 0.27 + (income - 67700) * 0.30;
else if (income <= 307050)
tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +
(67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 +
(income - 141250) * 0.35;
else
tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +
(67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 +
(307050 - 141250) * 0.35 + (income - 307050) * 0.386;
}
else if (status == 1) { // Compute tax for married file jointly,
// married separately, and head of household Left as exercise
}
else if (status == 2) { }
else if (status == 3) { }
else {
System.out.println("Error: invalid status");
System.exit(0);
}
// Display the result
JOptionPane.showMessageDialog(null, "Tax is " +
(int)(tax * 100) / 100.0,
"Example 3.1 Output", JOptionPane.INFORMATION_MESSAGE);
}
}
One can write a switch statement to replace a nested if statement. For example,
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);
} // checks if status matches the values 0, 1, 2, or 3 respectively.
status is 0
Compute tax for single filers break
status is 1
Compute tax for married file jointly break
status is 2
Compute tax for married file separatly break
status is 3
Compute tax for head of household break
default
Default actions
Next Statement
FIGURE 3.5 The switch statement checks all cases and executes the statement in
matched cases
Caution
Do not forget to use a break statement when one is needed. For example, the
following code prints character a tree times if ch is ‘a’:
switch (ch) {
case ‘a’: System.out.println(ch);
case ‘b’: System.out.println(ch);
case ‘c’: System.out.println(ch);
}
3.2.5 Conditional Expressions
Conditional expressions are in different style, which no explicit if in the statement.
The syntax is shown below:
is equivalent to
y = (x > 0) ? 1 : -1;
For example:
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
is equivalent to
System.out.println((num % 2 == 0)? num + “is even” : num + “is
odd”);
For example:
Max = (num1 > num2) ? num1 : num2;
Note
The symbols ? and : appear together in a conditional expression. They form a
condition operator. The operator is called a ternary operator because it uses three
operands.
3.3 Loop Statements
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
FIGURE 3.6 The while loop repeatedly executes the statements in the loop body when
the loop-continuation-condition evaluates as true.
Caution
Make sure that the loop-continuation-condition eventually becomes false so that the
program will terminate.
A common programming error involves infinite loops.
data = Integer.parseInt(dataString);
data = Integer.parseInt(dataString);
}
System.exit(0);
}
}
If data is not 0, it is added to the sum and the next input data are read. If data is 0,
the loop body is not executed and the while loop terminates.
If the first input read is 0, the loop body never executes, and the resulting sum is
0.
The do-while loop executes the loop body first, and then checks the loop-
continuation condition to determine whether to continue or terminate the loop.
Caution
Don’t use floating-point values for equality checking in a loop control. Since
floating-point values are approximations, using them could result in imprecise
counter values and inaccurate results. This example uses int value for data. If a
floating-point type value is used for data, (data != 0) may be true even though data is
0.
if (data == 0)
System.out.println("data is zero");
else
System.out.println("data is not zero");
Like pow, sqrt is a method in the Math class for computing the square root of a
number.
do {
// Loop body
Statement(s);
} while (continue-condition); // Do forget “;”
Statement(s)
(loop body)
true Loop
Continuation
Condition?
false
data = Integer.parseInt(dataString);
sum += data;
} while (data != 0);
System.exit(0);
}
}
Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");
Action-After-Each-Iteration i++
(A) (B)
FIGURE 3.9 A for loop performs an initial action one, then repeatedly executes the
statements in the loop body, and performs an action after an iteration when the loop-
continuation-condition evaluates as true
Example: The following while loop prints Welcome to Java! 100 times.
int i = 0;
while (i < 100) {
System.out.println("Welcome to Java! ”);
i++;
}
Example: The following for loop prints Welcome to Java! 100 times.
int i;
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java! ”);
}
o The for loop initializes i to 0, then repeatedly executes the println and
evaluates i++ if i is less than 100.
o The initial-action, i = 0, initializes the control variable, i.
o The loop-continuation-condition, i < 100, is a Boolean expression.
o The expression is evaluated at the beginning of each iteration.
o If the condition is true, execute the loop body. If it is false, the loop terminates
and the program control turns to the line following the loop.
o The action-after-each-iteration, i++, is a statement that adjusts the control
variable.
o This statement is executed after each iteration. It increments the control variable.
o Eventually, the value of the control variable forces the loop-continuation-
condition to become false.
o The loop control variable can be declared and initialized in the for loop as
follows:
Note
Note
System.exit(0);
}
}
o The for loop repeatedly adds the control variable i to the sum. This variable,
which begins with 0.01, is incremented by 0.01 after each iteration. The loop
terminates when i exceeds 1.0.
o The exact sum should be 50.50, but the answer is 50.499985. The result is not
precise because computers use a fixed number of bits to represent floating-point
numbers, and thus cannot represent some floating-point number exactly.
output += "\n";
// Print table body
for (int i = 1; i <= 9; i++) {
output += i + " | ";
for (int j = 1; j <= 9; j++) {
// Display the product and align properly
if (i * j < 10)
output += " " + i * j;
else
output += " " + i * j;
}
output += "\n";
}
// Display result
JOptionPane.showMessageDialog(null, output,
"Example 3.4 Output", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
o The program displays a title on the first line and dashes on the second line. The
first for loop displays the numbers 1 – 9 on the third line.
o The next loop is a nested for loop with the loop with the control variable i in the
outer loop and j in the inner loop.
o For each i, the product i * j is displayed on a line in the inner loop, with j being 1,
2, 3, …, 9.
o The if statement in the inner loop is used so that the product will be aligned
properly.
o If the product is a single digit, it is displayed with an extra space before it.
The three forms of loop statements, while, do, and for, are expressively equivalent;
that is, you can write a loop in any of these three forms.
For example, a while loop in (A) in the following figure can always be converted
into the following for loop in (B):
A for loop in (A) in the following figure can generally be converted into the
following while loop in (B) except in certain special cases.
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(A) (B)
Recommendations
The author recommends that you 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.
Caution
Adding a semicolon at the end of the for clause before the loop body is a common
mistake, as shown below:
int i=0;
while (i<10); // Logic Error (‘;’)
{
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++;
} while (i<10); // Correct, The semicolon is needed
3.6 Using the Keywords break and continue
The break control immediately ends the innermost loop that contains it. It is
generally used with an if statement.
The continue control only ends the current iteration. Program control goes to the
end of the loop body. This keyword is generally used with an if statement.
The break statement forces its containing loop to exit.
false
Continuation
condition?
true
Statement(s)
break
Statement(s)
Next
Statement
The continue statement forces the current iteration of the loop to end.
false
Continue
condition?
true
Statement(s)
continue
Statement(s)
Next
Statement
Page 102, EXAMPLE 3.5 Demonstrating a break Statement
// TestBreak.java: Test the break keyword in the loop
public class TestBreak {
/** Main method */
public static void main(String[] args) {
int sum = 0;
int item = 0;
The sum is 6
o Without the if statement, this program calculates the sum of the numbers
from 1 to 5. But with the if statement, the loop terminates when the sum
becomes greater than or equal to 6.
The sum is 13
Every Statement in Java can have an optional label as an identifier. Labels are often
used with break and continue statements.
You can use a break statement with a label to break out of the labeled loop, and a
continue statement with a label to break out of the current iteration of the labeled
loop.
The break statement given below, for example, breaks out of the outer loop if (i *
j) > 50 and transfers control to the statement immediately following the outer loop.
outer:
for (int i = 1; i < 10; i++) {
inner:
for (int j = 1; j < 10; j++) {
if (i * j > 50)
break outer;
System.out.println(i * j);
}
}
If you replace break outer with break in the preceding statement, the break statement
would break out of the inner loop and continue to stay inside the outer loop.
The following continue statement breaks out of the inner loop if (i * j > 50) and starts
a new iteration of the outer loop if i < 10 is true after i us incremented by 1:
outer:
for (int i = 1; i < 10; i++) {
inner:
for (int j = 1; j < 10; j++) {
if (i * j > 50)
continue outer;
System.out.println(i * j);
}
}
If you replace continue outer with continue in the preceding statement, the continue
statement would break out of the current iteration of the inner loop if (i * j > 50)
and continue the next iteration of the inner loop if j < 10 is true after j is incremented
by 1.