Saturday, November 9, 2013

Flow Controls - do while loop

As you just saw, if the conditional expression controlling a while loop in initially false, then the body of the loop will not be executed all However, sometime it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with, In other words, there are times when you would like to test the termination expression at the end of the loop rather then at the beginning, Fortunately, java has a loop that does that : the do while loop the do while loop always executes its body at least one, because its conditional expression is at the bottom of the loop. its general form is
do {
      // body
}while (condition );
Each 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, here is a reworked version of the "tick " program that demonstrates the do while loop.
class Dowhile{
            public static void main(String args[]){
                          int n = 10;
                          do {
                                       System.out.println("tick "+n);
                                       n--;
                           }while (n > 0);
                       
           }
}
It generates the same output as before. The loop in the above program, while technically correct, can be written efficiently as follows;
do {
           System.out.println("tick "+ n);
}while(--n >0 );
Here, the expression (--n >0) combines the decrements of n and the test for zero into one expression, here is how it works, First, the --n statement executes, decrements n and return the new value of n. this value is then compared with zero,  the loop continues, otherwise it terminates, a menu selection, because you will usually want the body of a menu loop to execute at least once, Consider the following example
class Menu {

    public static void main(String[] args) throws IOException {
        char c;
        do {
            System.out.println("Your name");
            System.out.println("Jone ");
            System.out.println("karina");
            System.out.println("max");
            System.out.println("chose one :");
            c = (char) System.in.read();
        } while (c < '1' || c > '3');
        System.out.println("\n");
        switch (c) {
            case '1':
                System.out.println("My Name is Jone");
                break;
            case '2':
                System.out.println("My Name is Karina ");
                break;
            case '3':
                System.out.println("My name is max");
        }
    }
}

Output 
Your name
Jone
karina
max
chose one :
1

My Name is Jone

In the program, the do while loop is used to verify that the user has entered a valid choice if not, then the user is re prompted. Sine the menu must be displayed  at least once, the do while is the perfect loop to accomplish this
A few other points about this example Notice that characters are read from the keyboard by calling System.in.read(); this is one of java's console input functions, Although java's console I/O methods won't be discussed till the later System.in.read(); is used here to obtain the user;s choice it reads characters form standard input ( returned as integers, which is why the return value was cast to char ) . By default. standard input is line buffered, so you must press ENTER before any characters that you type will be sent to you program.java's console input can be a bit awkward to work with. Further. most real world program and applets will be graphical and window based For these reasons, not much use of console input has been made in this However , is is useful in this context point to consider because System.in.read(); is being used, the program must specify the throw java.io.IOException clause, This line is necessary to handle input errors, it is part Java's exception handling features, which are discussed later.

No comments:

Post a Comment