Java Reference
In-Depth Information
{
...
while (next >= 0)
{
next = keyboard.nextInt( );
if (next < -100)
break outerLoop;
...
}
...
answer = ...
} while (answer.equalsIgnoreCase("yes"));
The identifier outerLoop labels the outer loop, which is a do loop. If the number read
into the variable next is negative but not less than -100, then the inner while loop
ends normally. If, however, the number read is less than -100, then the labeled break
statement is executed, and that ends the enclosing do loop.
You can actually label any statement, not just loop statements and switch state-
ments. A labeled break will always end the enclosing statement with the matching
label, no matter what kind of statement is labeled.
The labeled break can be handy when you have a switch statement in the body of
a loop and you want a break statement that ends the loop rather than just ending the
switch statement.
The exit Statement
The break statement ends a loop (or switch statement), but does not end the pro-
gram. The following statement immediately ends the program:
System.exit(0);
System is a predefined Java class that is automatically provided by Java, and exit is a
method in the class System . The method exit ends the program as soon as it is invoked.
In the programs that we will write, the integer argument 0 can be any integer, but by tra-
dition we use 0, because 0 is used to indicate a normal ending of the program.
The following is a bit of code that uses the exit statement:
System.out.println("Enter a negative number:");
int negNumber = keyboard.nextInt( );
if (negNumber >= 0)
{
System.out.println(negNumber + " is not a negative number.");
System.out.println("Program aborting.");
System.exit(0);
}
There are more examples of the use of System.exit in Chapter 4.
Search WWH ::




Custom Search