Java Reference
In-Depth Information
System.out.println(
"The smallest factor other than 1 for "
+ n +
" is "
+ factor);
You may rewrite the code without using
break
as follows:
boolean
found =
false
;
int
factor =
2
;
while
(factor <= n &&
!found
) {
if
(n % factor ==
0
)
found =
true
;
else
factor++;
}
System.out.println(
"The smallest factor other than 1 for "
+ n +
" is "
+ factor);
Obviously, the
break
statement makes this program simpler and easier to read in this case.
However, you should use
break
and
continue
with caution. Too many
break
and
continue
statements will produce a loop with many exit points and make the program diffi-
cult to read.
Note
Some programming languages have a
goto
statement. The
goto
statement indiscrimi-
nately transfers control to any statement in the program and executes it. This makes
your program vulnerable to errors. The
break
and
continue
statements in Java are
different from
goto
statements. They operate only in a loop or a
switch
statement.
The
break
statement breaks out of the loop, and the
continue
statement breaks out
of the current iteration in the loop.
goto
4.22
✓
✓
What is the keyword
break
for? What is the keyword
continue
for? Will the fol-
lowing programs terminate? If so, give the output.
Check
Point
int
balance =
10
;
while
(
true
) {
if
(balance <
9
)
continue;
balance = balance -
9
;
int
balance =
10
;
while
(
true
) {
if
(balance <
9
)
break;
balance = balance -
9
;
}
}
System.out.println(
"Balance is "
+ balance);
System.out.println(
"Balance is "
+ balance);
(a)
(b)
4.23
The
for
loop on the left is converted into the
while
loop on the right. What is
wrong? Correct it.
int
i =
0
;
while
(i <
4
) {
if
(i %
3
==
0
)
continue
;
sum += i;
i++;
for
(
int
i =
0
; i <
4
; i++) {
if
(i %
3
==
0
)
continue
;
sum += i;
Converted
Wrong conversion
}
}