Java Reference
In-Depth Information
for (double d = 0.0; d != 1.0; d += 0.1)
However, there are times when it is handy to code a loop as if it were infinite by
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.
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 =;
if (ch == 'C' || ch == 'c')
The break statement is also useful in the context ofa finite loop. Forexample, con-
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;
eeSearchID+" exists"
Search WWH ::

Custom Search