Menu driven program in java , All Information 2023
coding ProgramingWhat Is menu driven program in java
A menu-driven program in Java is a program that presents a user with a menu of options, typically displayed as a list of choices on the screen, and allows the user to select one of those options by entering a number or selecting a button or option.
The menu usually offers a set of actions or functions that the user can choose from to perform a specific task. Once the user selects an option, the program will execute the corresponding code or function.
For example, a menu-driven program could present the user with options to:
1. Create a new file
2. Open an existing file
3. Edit a file
4. Save a file
5. Print a file
6. Exit the program
The user can then select an option by entering a number or selecting a button, and the program will perform the corresponding action. The implementation of the program usually involves using control statements such as if-else or switch statements to execute the selected action.
MENU DRIVEN PROGRAM IN JAVA
I can provide an example of a menu-driven program in Java. In this example, we will create a program that displays a menu of options to the user and performs the selected action.
import java.util.Scanner;
public class MenuDrivenProgram {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Display the menu
System.out.println("Menu:");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Option 3");
System.out.println("4. Exit")
// Loop until the user selects the "Exit" option
boolean exit = false;
while(!exit) {
// Prompt the user to enter a choice
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
// Execute the selected action
switch(choice) {
case 1:
System.out.println("You selected Option 1");
break;
case 2:
System.out.println("You selected Option 2");
break;
case 3:
System.out.println("You selected Option 3");
break;
case 4:
System.out.println("Exiting program...");
exit = true;
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
}
// Close the Scanner object
scanner.close();
In this example, we first display a menu of options to the user using the System.out.println() method. We then create a Scanner object to read user input.
We use a while loop to repeatedly prompt the user to enter a choice until they select the "Exit" option. Within the loop, we use a switch statement to execute the selected action.
If the user selects Option 1, 2, or 3, we simply display a message indicating which option they selected. If the user selects Option 4, we set the exit variable to true to exit the loop and the program.
If the user enters an invalid choice, we display an error message and prompt the user to try again. Finally, we close the Scanner object to release its resources.