Simple Java Menu

This is another simple Java example on how to implement a console menu interface with the user.
The steps are really simple.
In a loop:
a) A String which contains the menu options is printed.
b) A number from keyboard is read.
c) Using switch - case statement the correct method is called.
The following Java code is showing the above steps.

import java.util.Scanner;

public class SimpleMenu {
public void start(){
Scanner keyboard = new Scanner(System.in);
int choice;
String menu = "Options\n";
menu+="1. Choice1\n";
menu+="2. Choice2\n";
menu+="3. Choice3\n";
menu+="4. Exit\n";
menu+="Select an option : ";
while(true) {
choice = keyboard.nextInt();
switch (choice) {
case 1: choice1(); break;
case 2: choice2(); break;
case 3: choice3(); break;
case 4: System.exit(0); break;
System.out.println("Invalid choice.");

private void choice1(){
System.out.println("Menu example choice 1");
private void choice2(){
System.out.println("Menu example choice 2");
private void choice3(){
System.out.println("Menu example choice 3");

public static void main(String[] args) {
new SimpleMenu().start();

1 comment:

minanov said...

Very interesting, I will try that to see how it works

Related Posts Plugin for WordPress, Blogger...