This project demonstrates a simple text-based menu in Java, where users can choose from multiple options using a switch statement. The program provides a menu, takes user input, and processes different commands accordingly. The menu allows users to choose between different menu items or quit the program.
- Simple text menu with options.
- Switch-case structure for handling user choices.
- Validates user input to ensure it is a valid menu item.
- The program prints a menu with numbered options.
- The user is prompted to choose a menu item (1, 2, or 0 to quit).
- Based on the input, the corresponding case in the
switch
statement is executed. - The program continues to prompt the user until they choose to quit (option 0).
1. Menu item #1
2. Menu item #2
0. Quit
Choose menu item: 1
You've chosen item #1
import java.util.Scanner;
public class SwitchOperatedTextMenu {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// print menu
for (int i = 1; i <= 2; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
// handle user commands
boolean quit = false;
int menuItem;
do {
System.out.print("Choose menu item: ");
menuItem = in.nextInt();
switch (menuItem) {
case 1:
System.out.println("You've chosen item #1");
// do something...
break;
case 2:
System.out.println("You've chosen item #2");
// do something...
break;
case 0:
quit = true;
break;
default:
System.out.println("Invalid choice.");
}
} while (!quit);
System.out.println("Bye-bye!");
}
}
-
Clone the repository:
git clone https://github.com/your-username/SwitchOperatedTextMenu.git
-
Navigate to the project directory:
cd SwitchOperatedTextMenu
-
Compile the Java file:
javac SwitchOperatedTextMenu.java
-
Run the program:
java SwitchOperatedTextMenu
Feel free to fork the repository, submit issues, and create pull requests. Contributions are welcome!
This project is licensed under the MIT License.