Loop do while: the control statement that always happens...at least once


We will see in this article another important loop in Java, do ... while loop that always executes the code of the loop at least once, regardless of the condition of the while being true or false.



One of the biggest problems of the while loop is that it is only executed if the condition contained in it is true.
But often, in our Java applications, we can not guarantee that this condition will always be true or want the loop to run AT LEAST ONCE, and if the user decides the loop will continue or not.

Then the differential tie while he is always running, always starts the loop.

How to use the do while looping

The syntax of the loop .. while in Java, is as follows
do
{
 //this code will execute at least once    
} while( condition );


Its use is very simple and intuitive, since the while loop we already know.
That is, this loop tells us 'do it while condition is true'

Examples of use 

One example of use is to display the menu. However, the menu must be displayed at least once.
If later you want to leave, it's your choice.
But he has to appear at least once, he has. And a good solution to do this in Java is to use the loop do... while.

In the following example, the menu is displayed.
To stop displaying the menu, simply enter 0, the boolean will become 'false' and the loop does not happen again, because the condition inside the while is false.
If the user input is any number other than 0, the boolean variable remains 'true', as has been stated and the loop will continue to run (i.e., the menu continues to be displayed).

The excerpt:
System.out.printf ("\n \n \n \n \n \n"); 
It is simply to clear the screen.

Test to see:


import java.util.Scanner;

public class DoWhile {
    public static void main(String[] args) {
        boolean continue=true;
        int option;
        Scanner input = new Scanner(System.in);
        do
        {
            System.out.println("\t\tOption menu of the Progressive Java course:");
            System.out.println("\t1. See the menu");
            System.out.println("\t2. Read he menu");
            System.out.println("\t3. Repeat the menu");
            System.out.println("\t4. Again");
            System.out.println("\t5. I didn't read, could you repeat?");
            System.out.println("\t0. Out");
            
            System.out.print("\nType your choice: ");
            option = input.nextInt();
            
            if(option == 0){
                continue = false;
                System.out.println("Program finished");
            }
            else{
                System.out.printf("\n\n\n\n\n\n");
            }
            
        } while( continue );
    }

}



Although this is a simple example, it is the basis for several menus that we do in our Java course.
For example, as a system of registration of students and an ATM scheme....

No comments: