The last of Java’s loops is the do-while. Unlike the for and the while loops, in which the condition is tested at the top of the loop, the do-while loop checks its condition at the bottom of the loop. This means that ado-while loop will always execute at least once. The general form of the do-while loop is
do
{
statements;
}
while(condition);
Although the braces are not necessary when only one statement is present, they are of ten used to improve read ability of the do-while construct,thus preventing confusion with the while. The do-while loop executes as long as the conditional expression is true. The following program loops until the user enters the letter q.
// Demonstrate the do-while loop.
class DWDemo
{
public static void main(String args[])
throws java.io.IOException
{
char ch;
do { System.out.print("Press a key followed by ENTER: ");
ch = (char)
System.in.read();
// get a char
}
while(ch != 'q');
}
}
Using ado-while loop, we can further improve the guessing game program from earlier in this module. This time, the program loops until you guess the letter.
// Guess the letter game, 4th version.
class Guess4
{
public static void main(String args[])
throws java.io.IOException
{
char ch, answer = 'K';
do
{
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it: ");
// read a letter, but skip cr/lf
do
{
ch = (char) System.in.read();
// get a char
}
while(ch == '\n' | ch == '\r');
if(ch == answer)
System.out.println("** Right **");
else
{
System.out.print("...Sorry, you're ");
if(ch < answer)
System.out.println("too low");
else
System.out.println("too high");
System.out.println("Try again!\n");
}
}
while(answer != ch);
}
}
Here is a sample run:
I'm thinking of a letter between A and Z. Can you guess it: A ...Sorry, you're too low Try again!
I'm thinking of a letter between A and Z. Can you guess it: Z ...Sorry, you're too high Try again!
I'm thinking of a letter between A and Z. Can you guess it: K ** Right **
Notice one other thing of interest in this program. The do-while loop shown here obtains the next character, skipping over any carriage return and line feed characters that might be in the input stream:
// read a letter, but skip cr/lf
do
{
ch = (char)
System.in.read();
// get a char
}
while(ch == '\n' | ch == '\r');
Here is why this loop is needed: As explained earlier,System. in is line buffered—you have to press ENTER before characters are sent. Pressing ENTER causes a carriage return and a line feed character to be generated. These characters are left pending in the input buffer. This loop discards those characters by continuing to read input until neither is present.
hi
ReplyDelete