Java program for do while loop
Program Description
Write a java program for do while demo. In this page, we will write a simple java program to demonstrate the do-while-loop.
Syntax
General syntax of the do-while is shown below. The expression evaluation is done after the loop. So the do-while is executed at least once irrespective of the loop condition.
do
{
//statements
} while (Boolean_expression);
Java Program
Lets write a simple program to display a menu to user and display it until user choose to quit the loop. We will make use of the do while loop in the program.
import java.util.Scanner; //------------------------------------ // DoWhileDemo.java // www.TestingDocs.com // Program to demo do while loop //------------------------------------- public class DoWhileDemo { public static void main(String[] args) { int choice; // to take choice input Scanner keyboard= new Scanner(System.in); do { System.out.println("~~~~~~~~ Menu ~~~~~~~~"); System.out.println("1. Option 1"); System.out.println("2. Option 2"); System.out.println("3. Quit"); System.out.println("Enter choice ="); choice=keyboard.nextInt(); if(choice==1) { System.out.println("User entered 1"); } if(choice==2) { System.out.println("User entered 2"); } }while(choice != 3); } }
Program Output
~~~~~~~~ Menu ~~~~~~~~
1. Option 1
2. Option 2
3. Quit
Enter choice =
1
User entered 1
~~~~~~~~ Menu ~~~~~~~~
1. Option 1
2. Option 2
3. Quit
Enter choice =
2
User entered 2
~~~~~~~~ Menu ~~~~~~~~
1. Option 1
2. Option 2
3. Quit
Enter choice =
3