Java Reference
In-Depth Information
d)
for
(i =
1
; i <=
20
; i++)
{
System.out.print(i);
if
(i %
5
==
0
)
System.out.println();
else
System.out.print(
'\t'
)
;
}
5.4
a)
Error: The semicolon after the
while
header causes an infinite loop, and there's a miss-
ing left brace.
Correction: Replace the semicolon by a
{
, or remove both the
;
and the
}
.
b)
Error: Using a floating-point number to control a
for
statement may not work, because
floating-point numbers are represented only approximately by most computers.
Correction: Use an integer, and perform the proper calculation in order to get the values
you desire:
for
(k =
1
; k !=
10
; k++)
System.out.println((
double
) k /
10
);
c)
Error: The missing code is the
break
statement in the statements for the first
case
.
Correction: Add a
break
statement at the end of the statements for the first
case
. This
omission is not necessarily an error if you want the statement of
case
2:
to execute every
time the
case
1:
statement executes.
d)
Error: An improper relational operator is used in the
while
's continuation condition.
Correction: Use
<=
rather than
<
, or change
10
to
11
.
Exercises
5.5
Describe the four basic elements of counter-controlled repetition.
5.6
Compare and contrast the
while
and
for
repetition statements.
5.7
Discuss a situation in which it would be more appropriate to use a
do
…
while
statement
than a
while
statement. Explain why.
5.8
Compare and contrast the
break
and
continue
statements.
5.9
Find and correct the error(s) in each of the following segments of code:
a)
For
(i =
100
, i >=
1
, i++)
System.out.println(i);
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
(i =
19
; i >=
1
; i +=
2
)
System.out.println(i);