As you just saw, if the.conditional expression con(while Joop is initially false  then the body of the loop will not be executed at However, sometimes it is desirable
to  the body of a while loop' at least on get even if the conditional expression 'ls . false to begin with. In other words, there arc  you would like to test the  termination expression at the end of the loop rather than ~t the beginning. Fortunately  Java supplies'a loop that does just that: the do-while. The do-while loop always   executes its body at least once, because its conditional expression is at the bottom o f the loop. Its general form is iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression, Is true, the loop will repeat. Otherwise, the loop terminates, As with all of Java's loops, condition must be a Boolean  expression. "t  Here is a reworked version of the "tick" program that demonstrates the do-while loop. It generates the same output as before.

In this example, the' expression (- -n > 0) combines the decrement of n and the test for zero into one expression. Here is how it works. First, then statement executes
decremented n and returning the new value of n. This value is then compared with zero. If it is greater than zero, the loop continues; otherwise it terminates.  The do-while loop is especially useful when you process a menu selection, because you will usually want the body of a menu loop to execute at least once. Consider the following program which implements a very simple help system for Java's election and iteration statements:

In the  verify. that the use~ has valid . choice. If not, then the user is;reprompted. Since.the menu must be displayed at Ieast .once, the do-while is the perfect loop to accomplish this A few other points about this 'example: -Notice that characters are rend from the keyboardby calling This is one of java sconsole input functions Although Java's console I/O methods' won't be discussed in detail until  System read() js lsed here to obtain the user's choice. It readscharacters from . standard input (returned as integers, which is why the return value wascast  o char)  .By default, standard input is line buffered, so you must press ENTER before any  characters that you type-will be sent to your program. Java's' console input is quite limited and awkward to work with. Further, most  real-world Java programs and applets will be graphical arid window-based. For these reasons, not much use of console input has been made in this book. However, it is  useful in this context. One other point: Because is being used, t program' must specify the throws clause. This line is handle input errors. It is part of Java's exception handling .

Share This