Java Reference
In-Depth Information
Listing 5-15. A more complete while loop
int counter = 0;
while (counter < 10) {
System.out.println(counter);
counter++;
}
That (still simple) example shows the typical structure of a while loop: declare a variable, test the
variable at the top of the while loop, do some work in the while loop, and increment the variable in the
while loop. After the test fails, the while loop is done, and the code below the while loop runs.
You can create a while loop that runs forever (or, more likely, until some condition that gets checked
by an if statement in the body of the loop triggers a break statement) by using while(true) . That
construct is useful in some cases, but it's not a safe thing to do. Savvy programmers try to ensure that
loops can't run forever (that's called an infinite loop). What if, due to unexpected input data, your break
condition in the body of the loop never gets hit? Then your program is stuck (and that can be loads of fun
if it happens to be writing into a file—you can quickly cause problems for your operating system this
way). If you feel that you must use while(true) , test thoroughly.
Another use for a while loop is to try something for a set amount of time when you don't know how
long each try will take. For example, suppose a mail client tries for one minute to connect to a mail
server and then gives up (that is, it times out). Listing 5-14 shows one way to wait for a connection.
Listing 5-14. While loop that waits for an event
boolean connected = false;
long now = System.currentTimeMillis();
long oneMinuteFromStart = System.currentTimeMillis() + 60000;
while (!connected && now < oneMinuteFromStart) {
System.out.println("Trying to connect....");
if (MailServer.connect()) {
connected = true;
break;
}
// pause for two seconds
// to let other processes work, too
try {
System.out.println("(letting other processes run)");
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
// reset now for the next comparison
now = System.currentTimeMillis();
}
if (connected) {
System.out.println("Connected to the mail server");
} else {
System.out.println("Timed out while trying to connect to the mail server");
}
Search WWH ::




Custom Search