SAK3100_chapter5_sem10910
Download
Report
Transcript SAK3100_chapter5_sem10910
Chapter 5
Control Statements
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
1
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.
To implement selection control using switch statements.
To write expressions using the conditional operator.
To use while, do-while, and for loop statements to control the
repetition of statements.
To write nested loops.
To know the similarities and differences of three types of loops.
To implement program control with break and continue.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
2
Selection Statements
if Statements
switch Statements
Conditional Operators
3
Example
Example
if the radius is positive
computes the area and display
result;
4
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);
}
Boolean
Expression
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)
5
Note
Outer parentheses required
if ((i > 0) && (i < 10)) {
System.out.println("i is an " +
+ "integer between 0 and 10");
}
(a)
Braces can be omitted if the block contains a single
statement
Equivalent
if ((i > 0) && (i < 10))
System.out.println("i is an " +
+ "integer between 0 and 10");
(b)
6
Comparison Operators
Operator
Name
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equal to
!=
not equal to
7
Boolean Operators
Operator
Name
!
not
&&
and
||
or
^
exclusive or
8
Truth Table for Operator !
p
!p
true
false
!(1 > 2) is true, because (1 > 2) is false.
false
true
!(1 > 0) is false, because (1 > 0) is true.
Example
9
Truth Table for Operator &&
p1
p2
p1 && p2
false
false
false
false
true
false
true
false
false
true
true
true
Example
(3 > 2) && (5 >= 5) is true, because (3 >
2) and (5 >= 5) are both true.
(3 > 2) && (5 > 5) is false, because (5 >
5) is false.
10
Truth Table for Operator ||
p1
p2
p1 || p2
false
false
false
false
true
true
true
false
true
true
true
true
Example
(2 > 3) || (5 > 5) is false, because (2 > 3)
and (5 > 5) are both false.
(3 > 2) || (5 > 5) is true, because (3 > 2)
is true.
11
Truth Table for Operator ^
p1
p2
p1 ^ p2
false
false
false
false
true
true
true
false
true
true
true
false
Example
(2 > 3) ^ (5 > 1) is true, because (2 > 3)
is false and (5 > 1) is true.
(3 > 2) ^ (5 > 1) is false, because both (3
> 2) and (5 > 1) are true.
12
Write the output of the following program:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
public class TestBoolean {
public static void main (String[] args) {
int number = 18;
System.out.println(“Is ” + number + “:” +
“\ndivisible by 2 and 3? ” + (number % 2 ==
0 && number % 3 == 0) + “\ndivisible by 2 or 3? ” +
(number % 2 == 0 || number % 3 == 0) +
“\ndivisible by 2 or 3, but not both? ” +
(number % 2 == 0 ^ number % 3 == 0));
}
}
13
TestBoolean program output:
14
The & and | Operators
&&: conditional AND operator
&: unconditional AND operator
exp1 && exp2
(1 < x) && (x < 100)
(1 < x) & (x < 100)
15
The & and | Operators
||: conditional OR operator
|: unconditional OR operator
exp1 && exp2
(1 < x) || (x < 100)
(1 < x) | (x < 100)
16
The & and | Operators
p1 && p2, Java first evaluates p1 and then evaluates p2
if p1 is true; if p1 is false, it does not evaluate p2.
p1 || p2, Java first evaluates p1 and then evaluates p2 if
p1 is false; if p1 is true, it does not evaluate p2.
For & and | operators, & same as && and | same as ||
BUT & and | are evaluated for both operands.
17
The & and | Operators: Exercise
1.If x is 1, what is x after the
evaluation of the following
expression?
(x > 1) & (x++ > 1)
2.If x is 1, what is x after the
evaluation of the following
expression?
(x > 1) && (x++ > 1)
18
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);
}
This mistake is hard to find, because it is not a compilation error or
a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
19
Leap Year?
A year is a leap year if it is divisible by 4 but not by
100 or if it is divisible by 400.
The source code of the program is given below.
boolean isLeapYear =
((year % 4 == 0) && (year % 100 != 0)) ||
(year % 400 == 0);
20
Finding Leap Year
Leap Year program:
import javax.swing.JOptionPane;
public class LeapYear {
public static void main(String args[]) {
// Prompt the user to enter a year
String yearString = JOptionPane.showInputDialog("Enter a year");
// Convert the string into an int value
int year = Integer.parseInt(yearString);
// Check if the year is a leap year
boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
// Display the result in a message dialog box
JOptionPane.showMessageDialog(null, year + " is a leap year? " + isLeapYear);
}
}
Output:
21
The if...else Statement
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
true
Statement(s) for the true case
Boolean
Expression
false
Statement(s) for the false case
22
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");
}
23
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';
Program example:
24
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)
What is the output of the above program statement?
25
Note, cont.
Nothing is printed from the preceding statement. 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");
This statement prints B.
26
TIP
if (number % 2 == 0)
even = true;
else
even = false;
(a)
Equivalent
boolean even
= number % 2 == 0;
(b)
Program example:
27
CAUTION
if (even == true)
System.out.println(
"It is even.");
(a)
Equivalent
if (even)
System.out.println(
"It is even.");
(b)
Program example:
28
Example: 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 below.
The if…else structure:
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
}
29
Example: Computing Taxes
Algorithm:
1. Read status and income.
2. Compute tax based on status.
if (status==0) {
// Compute tax for single filers
if (income<6000)
tax=incomeX0.10;
else if (income<=27950)
tax=6000X0.10+(income-6000)*0.15;
.
.
.
else
tax=6000X0.10+(29500-6000)X0.15+(67700-27950)X0.27+(141250-67700)X0.30+(307050-141250)*0.35+(income-307050)X0.368
}
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
}
3. Display tax.
Refer ComputeTaxWithSelectionStatement.java page 105, Liang Text Book for the Java program
30
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);
}
31
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
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.
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;
}
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.
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.
34
switch Example
35
switch Example
switch (ch) {
case ‘a’: System.out.println(ch);
case ‘b’: System.out.println(ch);
case ‘c’: System.out.println(ch);
}
What is the output of the above program segment if ch is ‘a’?
36
if (x > 0)
y=1
else
y = -1;
Conditional Operator
is equivalent to
(booleanExp) ? exp1 : exp2
y = (x > 0) ? 1 : -1;
(booleanExpression) ? expression1 : expression2
Program example:
37
Conditional Operator
The statement:
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
is equivalent to the statement:
System.out.println((num % 2 == 0)? num + “is even” : num + “is odd”);
Program example:
38
Operator Precedence and Associativity
Operator precedence and associativity determine
the order in which operators are evaluated.
39
Operator Precedence
var++, var– (Postfix)
+, - (Unary plus and minus), ++var,--var (Prefix)
(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
& (Unconditional AND)
^ (Exclusive OR)
| (Unconditional OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)
40
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When
evaluating an expression without parentheses, the
operators are applied according to the precedence rule and
the associativity rule.
If operators with the same precedence are next to each
other, their associativity determines the order of
evaluation. All binary operators except assignment
operators are left-associative.
41
Operator Associativity
When two operators with the same precedence
are evaluated, the associativity of the operators
determines the order of evaluation. All binary
operators except assignment operators are leftassociative.
a – b + c – d is equivalent to ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))
42
Operator Precedence
How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?
43
Example
Applying the operator precedence and associativity rule,
the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as
follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
3 + 4 * 4 > 5 * 7 – 1
3 + 16 > 5 * 7 – 1
(1) inside parentheses first
(2) multiplication
(3) multiplication
3 + 16 > 35 – 1
19 > 35 – 1
19 > 34
false
(4) addition
(5) subtraction
(6) greater than
44
Operand Evaluation Order
The precedence and associativity rules
specify the order of the operators, but do not
specify the order in which the operands of a
binary operator are evaluated. Operands are
evaluated from left to right in Java.
The left-hand operand of a binary operator is
evaluated before any part of the right-hand
operand is evaluated.
45
Operand Evaluation Order, cont.
If
no operands have side effects that change the value of a
variable, the order of operand evaluation is irrelevant.
Interesting cases arise when operands do have a side effect.
For example,
x becomes 1 in the following code, because a is evaluated to 0
before ++a is evaluated to 1.
int a = 0;
int x = a + (++a);
But x becomes 2 in the following code, because ++a is evaluated
to 1, then a is evaluated to 1.
int a = 0;
int x = ++a + a;
46
Rule of Evaluating an Expression
· Rule 1: Evaluate whatever sub-expressions you can
possibly evaluate from left to right.
· Rule 2: The operators are applied according to their
precedence.
· Rule 3: The associativity rule applies for two
operators next to each other with the same precedence.
47
Rule of Evaluating an Expression
· Applying the rule, the expression 3 + 4 * 4 > 5 * (4 + 3)
- 1 is evaluated as follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
3 + 16 > 5 * (4 + 3) - 1
(1) 4 * 4 is the first subexpression that can
be evaluated from left.
(2) 3 + 16 is evaluated now.
19 > 5 * (4 + 3) - 1
19 > 5 * 7 - 1
(3) 4 + 3 is now the leftmost subexpression
that should be evaluated.
(4) 5 * 7 is evaluated now.
19 > 35 – 1
19 > 34
false
(5) 35 – 1 is evaluated now.
(6) 19 > 34 is evaluated now.
48
Repetitions
while
do-while Loops
for
Loops
Loops
break and continue
49
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
Statement(s)
(loop body)
(A)
false
(count < 100)?
false
true
System.out.println("Welcome to Java!");
count++;
(B)
50
Write an algorithm and a program that counts the sum of several input data and exit if input data is 0
ALGORITHM:
PROGRAM:
1.
2.
3.
4.
5.
1.
6.
7.
Start the processing
Read data
Convert data to integer number
Initialize sum = 0
Repeat reading until data = 0
5.1
Calculate sum
5.2
Read next data
Print sum
Stop the processing
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
OUTPUT:
16.
import javax.swing.JOptionPane;
public class SumIntegers {
public static void main(String[] args) {
String dataString = JOptionPane.showInputDialog
("Enter an int value:\n(the program exits if the input is 0)");
int data = Integer.parseInt(dataString);
int sum = 0;
while (data != 0) {
sum = sum + data;
dataString = JOptionPane.showInputDialog
("Enter an int value:\n(the program exits if the input is 0)");
data = Integer.parseInt(dataString);
}
JOptionPane.showMessageDialog(null, "The sum is "+ sum);
}
}
51
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.
// 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");
52
Exercise
Write an algorithm and a program using the while loop that prints the
numbers from 1 to 100. Program output:
1
2
3
…..
100
Write an algorithm and a program using the while loop to get the sum
of 1 to 100 integer numbers ( 1+2+3+..+100). Program output:
Sum of 1 to 100 = 5050
53
do-while Loop
Statement(s)
(loop body)
true
do {
// Loop body;
Loop
Continuation
Condition?
false
Statement(s);
} while (loop-continuation-condition);
54
A program that counts the sum of several input data and exit if input data is 0
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
import javax.swing.JOptionPane;
public class SumIntegers {
public static void main(String[] args) {
String dataString = JOptionPane.showInputDialog
("Enter an int value:\n(the program exits if the input is 0)");
int data = Integer.parseInt(dataString);
int sum = 0;
do {
sum = sum + data;
dataString = JOptionPane.showInputDialog
("Enter an int value:\n(the program exits if the input is 0)");
data = Integer.parseInt(dataString);
} while (data!=0);
JOptionPane.showMessageDialog(null, "The sum is "+ sum);
}
}
55
Exercise
Write an algorithm and a program using the do…while loop that prints
numbers from 100 to 1. Program output:
100
99
98
…..
1
Write an algorithm and a program using the do…while loop to get the
sum of odd numbers from 1 to 99 ( 1+3+..+99). Program output:
Sum of odd numbers from 1 to 99 = 2500
56
for Loops
for (initial-action; loopcontinuation-condition;
action-after-each-iteration) {
// loop body;
Statement(s);
}
Intial-Action
Loop
Continuation
Condition?
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++
(A)
(B)
false
57
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-eachiteration in a for loop can be a list of zero or more commaseparated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++)); // prints 1-99
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
58
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, I
recommend that you use the equivalent loop in (b) to avoid
confusion:
for ( ; ; ) {
// Do something
}
(a)
Equivalent
while (true) {
// Do something
}
(b)
59
Example 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.
import javax.swing.JOptionPane;
public class TestSum{
public static void main(String[] args) {
float sum = 0;
for (float i = 0.01f; i <= 1.0f; i = i + 0.01f)
sum = sum + i;
JOptionPane.showMessageDialog(null, "The sum is " + sum);
}
}
60
Exercise
Write a program using the for loop that prints the
numbers from 0.1 to 1.0. Program Output:
0.1 0.2 0.3 ….. 1.0
Write a program using the for loop to get the sum
of 0.1 to 1.0 integer numbers
( 0.1+0.2+0.3+..+1.0). Program Output:
Sum from 0.1 to 1.0 = 5.5
61
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. For example, a while loop in (A) in the following figure
can always be converted into the following for loop in (B):
while (loop-continuation-condition) {
// Loop body
}
Equivalent
(A)
for ( ; loop-continuation-condition; )
// Loop body
}
Example:
Convert the following while loop into a for loop:
int i=1;
int sum=0;
while (sum<10000) {
sum=sum+i;
i++;
}
convert while to for
(B)
int sum=0;
for (int i=1;sum<10000;i++)
sum=sum+i;
System.out.println(sum);
62
Which Loop to Use?
Exercise:
Convert the following while loop into a for loop:
int i=0;
long sum=0;
while (i<=1000) {
sum=sum+i;
i++;
}
63
Which Loop to Use?
Solution:
Convert the following while loop into a for loop:
int i=0;
long sum=0;
while (i<=1000) {
sum=sum+i;
i++;
convert while to for
long sum=0;
for (int i=0;i<=1000;i++)
sum=sum+i;
}
64
Which Loop to Use?
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 (will be discussed when
learning continue keyword, related to review question 4.12 in Liang text book):
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
(A)
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(B)
65
Recommendations
I recommend 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.
66
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
67
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);
68
Displaying the Multiplication Table
Problem: Write a program that uses nested for loops to print a multiplication table.
public class Mult {
public static void main (String[] args) {
for (int i=1; i<=9; i++) {
System.out.print("\n" +i);
for (int j=1; j<=9; j++)
System.out.print("\t" +(i*j));
System.out.println("");
}
}
}
Output:
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9
2
4
6
8
10
12
14
16
18
3
.
.
.
.
.
.
.
.
4
.
.
.
.
.
.
.
.
5
.
.
.
.
.
.
.
.
6
.
.
.
.
.
.
.
.
7
.
.
.
.
.
.
.
.
8
.
.
.
.
.
.
.
.
9
18
27
36
45
54
63
72
81
69
Exercise
Using
nested loop, write a program to
produce the following output:
70
The break Keywords
Continuation
condition?
false
break immediately ends the
innermost loop that contains it.
It is generally used with an if
statement
true
Statement(s)
break
Statement(s)
Next
Statement
71
The continue Keyword
Continue
condition?
true
false
continue only ends the current
iteration. Program control goes
to the end of the loop body. The
keyword is usually used with an
if statement.
Statement(s)
continue
Statement(s)
Next
Statement
72
Using break and continue
Examples for using the break and continue
keywords:
TestBreak.java
TestContinue.java
73
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
public class TestBreak {
public static void main(String[] args) {
int sum = 0, number = 0;
while (number < 5) {
number++;
sum += number;
if (sum >= 6)
break;
}
System.out.println(“The number is “ +
number);
System.out.println(“The sum is “ + sum);
}
}
74
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
public class TestContinue {
public static void main(String[] args) {
int sum = 0, number = 0;
while (number < 5) {
number++;
if (number % 2 == 0)
continue;
sum += number;
}
System.out.println(“The number is “ +
number);
System.out.println(“The sum is “ + sum);
}
}
75
Converting for to while for Special Cases
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 (see Review Question
4.12 for one of them):
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
Equivalent
(A)
(B)
Example (based on Review Question 4.12, pg. 146):
(1)
public class Original {
public static void main (String args[]) {
int sum=0;
for (int i=0;i<4;i++) {
if (i%3==0) continue;
sum+=i;
}
System.out.println(sum);
}
}
Output for (1) and (2) is 3
Converted
Correct
Conversion
(2)
public class Converted1 {
public static void main (String args[]) {
int sum=0, i=0;
while (i<4) {
if (i%3==0) {
i++;
continue;
}
sum+=i;
i++;
}
System.out.println(sum);
}
}
76
Example
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.
77
import javax.swing.JOptionPane;
public class GreatestCommonDivisor {
/** Main method */
public static void main(String[] args) {
// Prompt the user to enter two integers
String s1 = JOptionPane.showInputDialog("Enter first integer");
int n1 = Integer.parseInt(s1);
String s2 = JOptionPane.showInputDialog("Enter second integer");
int n2 = Integer.parseInt(s2);
int gcd = 1;
int k = 1;
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
k++;
}
String output = "The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd;
JOptionPane.showMessageDialog(null, output);
}
}
78
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 $30,000.
Since your base salary is $5,000, you have to make $25,000 in
commissions to earn $30,000 a year. What is the sales amount for a
$25,000 commission? You can find it if you know the sales amount.
79
import javax.swing.JOptionPane;
public class FindSalesAmount {
/** Main method */
public static void main(String[] args) {
// The commission sought
final double COMMISSION_SOUGHT = 25000;
final double INITIAL_SALES_AMOUNT = 0.01;
double commission = 0;
double salesAmount = INITIAL_SALES_AMOUNT;
do {
// Increase salesAmount by 1 cent
salesAmount += 0.01;
// Compute the commission from the current salesAmount;
if (salesAmount >= 10000.01)
commission =
5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;
else if (salesAmount >= 5000.01)
commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;
else
commission = salesAmount * 0.08;
} while (commission < COMMISSION_SOUGHT);
// Display the sales amount
String output =
"The sales amount $" + (int)(salesAmount * 100) / 100.0 +
"\nis needed to make a commission of $" + COMMISSION_SOUGHT;
JOptionPane.showMessageDialog(null, output);
}
}
80
Exercise
Write an algorithm and a program that reads an
unspecified number of positive integers, counts the
number of integers and finds the biggest and
smallest integer value. Your program ends with the
input -999. Use the while loop. An output example:
81
SOLUTION
import java.util.Scanner;
public class Counting
{
public static void main (String args[])
{
int counter=0, biggest=0, smallest=0;
Scanner scan=new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number=scan.nextInt();
while (number!=-999)
{
counter++;
if (number > biggest)
biggest=number;
if (number < biggest)
smallest=number;
System.out.print("Enter a positive integer: ");
number=scan.nextInt();
}
System.out.println("Number of integers = " + counter);
System.out.println("Biggest integer = " + biggest);
System.out.println("Smallest integer = " + smallest);
}
}
82
Exercise
Write a program that prompts the user to enter the
number of students and each student’s name and score,
and finally displays the student with the highest score.
Use the do…while loop. An output example:
83
SOLUTION
import javax.swing.JOptionPane;
public class Student
{
public static void main (String args[])
{
int input;
int counter=0;
int number;
int largest = 0;
String name=" ";
String student=" ";
input = Integer.parseInt(JOptionPane.showInputDialog("Enter number of students: "));
do
{
counter++;
name = JOptionPane.showInputDialog("Enter student's name: ");
number = Integer.parseInt(JOptionPane.showInputDialog("Enter student's score: "));
if (number >= largest) {
largest=number;
student=name;
}
}while (counter<input);
JOptionPane.showMessageDialog(null, "The highest score is " + student +" with the score " +largest);
}
}
84