We have already seen the break statement in the context of the switch statement. The break statement can also be used to exit out of a for, while, or do while loop. The SumOddArguments program sums all the arguments until the first even-valued argument
is reached.
SumOddArguments
public class SumOddArguments
{
public static void main(String[] args)
{
int arg;
int sum = 0;
for (int i = 0; i < args.length; i++)
{
arg = Integer.parseInt(args[i]);
if (arg % 2 == 0)
{
break;
}
sum = sum + arg;
}
System.out.println(''Sum of odd arguments is : " + sum);
}
}
SumOdd Arguments
In the for loop (lines 7–13), as soon as an even-valued argument has been reached, in line 9 arg % 2 is equal to 0; consequently, the break statement passes control to the first statement after the for loop, namely, line 14.
The continue statement passes control to the next iteration of the enclosing for, while, or do while loop. The following code fragment sums all odd integers from 1 to 10:
int sum = 0;
for (int i = 1; i < 11; i++)
{
if (i % 2 == 0)
{
continue;
}
sum = sum + i;
}
The continue statement ensures that, for an even number, the next statement, sum =sum + i, is skipped and thus sum is not incremented.If within nested loops, a break statement is used to exit out of one of the inner loops, then control passes to the next iteration of the enclosing loop. If the intention is to break out of two or more enclosing loops, then this can be achieved by a labeled break. The SumSomeArguments example sums all arguments until one argument is equal to one of the elements of the array intArray. The elements of intArray are set to 5 and 6. If arguments of 7, 8, 9, 5, and 3, say, are passed to the program, then the resulting sum equals
7 + 8 + 9 = 24.
SumSomeArguments
public class SumSomeArguments
{
public static void main(String[] args)
{
int intArray [];
int arg;
int sum = 0;
intArray = new int [2];
intArray[0] = 5;
intArray[1] = 6;
outerForLoop:
for (int i = 0; i < args.length; i++)
{
arg = Integer.parseInt(args[i]);
for (int j = 0; j < 2; j++) {
if (intArray[j] == arg) {
break outerForLoop;
}
}
sum = sum + arg;
}
System.out.println(''Sum of arguments = " + sum);
}
}
The label in line 11 is outerForLoop:. The syntax for a label is any valid identifier followed by a colon. The break label statement, break outerForLoop:, in line 16, will pass control to the statement following the statement identified by the label. The outerForLoop: statement refers to the entire outer for loop enclosed by braces, so control passes to the println statement in line 21. If we had used an unlabeled break in
the program, then control would have passed to line 19, and the program would have carried on adding the arguments to the sum.
Home
Break and Continue Statements
Java Flow Controls
3.3.4 Using break and continue Statements in Java
3.3.4 Using break and continue Statements in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment