Java Reference
In-Depth Information
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 con-
tinue statements will produce a loop with many exit points and make the program difficult
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
Note
Programming is a creative endeavor. There are many different ways to write code. In
fact, you can find a smallest factor using a rather simple code as follows:
int factor = 2 ;
while (factor <= n && n % factor != 0 )
factor++;
5.24
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 )
break ;
balance = balance - 9 ;
}
int balance = 10 ;
while ( true ) {
if (balance < 9 )
continue ;
balance = balance - 9 ;
}
System.out.println( "Balance is "
+ balance);
System.out.println( "Balance is "
+ balance);
(a)
(b)
5.25
The for loop on the left is converted into the while loop on the right. What is
wrong? Correct it.
int sum = 0 ;
for ( int i = 0 ; i < 4 ; i++) {
if (i % 3 == 0 ) continue ;
sum += i;
}
int i = 0 , sum = 0 ;
while (i < 4 ) {
if (i % 3 == 0 ) continue ;
sum += i;
i++;
}
Converted
Wrong conversion
5.26
Rewrite the programs TestBreak and TestContinue in Listings 5.12 and 5.13
without using break and continue .
 
Search WWH ::




Custom Search