Java Reference
In-Depth Information
for (double d = 0.0; d != 1.0; d += 0.1)
System.out.println(d);
However, there are times when it is handy to code a loop as if it were infinite by
usingoneoftheaforementionedprogrammingidioms.Forexample,youmightcodea
while(true) loopthatrepeatedly promptsforaspecific keystrokeuntilthecorrect
key is pressed. When the correct key is pressed, the loop must end. Java provides the
break statement for this purpose.
Thebreakstatementtransfersexecutiontothefirststatementfollowingaswitchstate-
ment (as discussed earlier) or a loop. In either scenario, this statement consists of re-
served word break followed by a semicolon.
The following example uses break with an if decision statement to exit a
while(true) -based infinite loop when the user presses the C or c key:
int ch;
while (true)
{
System.out.println("Press C or c to continue.");
ch = System.in.read();
if (ch == 'C' || ch == 'c')
break;
}
The break statement is also useful in the context ofa finite loop. Forexample, con-
siderascenariowhereanarrayofvaluesissearchedforaspecificvalue,andyouwant
to exit the loop when this value is found. The following example reveals this scenario:
int[] employeeIDs = { 123, 854, 567, 912, 224 };
int employeeSearchID = 912;
boolean found = false;
for (int i = 0; i < employeeIDs.length; i++)
if (employeeSearchID == employeeIDs[i])
{
found = true;
break;
}
System.out.println((found)
?
"employee
"+employ-
eeSearchID+" exists"
Search WWH ::




Custom Search