Java: MenuExample
MenuExample()
import java.util.Scanner;
public class MenuExample
{
String menuOptions = "123x";
public MenuExample()
{
menu();
}
private void menuDisplay()
{
System.out.println("MENU");
System.out.println();
System.out.println("1. Say Hello");
System.out.println("2. Do something else");
System.out.println("x. Exit Progranm ");
System.out.println();
System.out.print("Enter the menu option: ");
}
public void menu(){
String option;
do{
menuDisplay();
option = getOption();
doWork(option);
}while ((option.compareToIgnoreCase("x")!=0));
System.out.println("Thank you for using this program");
exitProgram();
}
private void exitProgram(){System.exit(1);}
private String getOption(){
String menuChoice;
Scanner kb = new Scanner(System.in);
menuChoice=kb.nextLine();
while(menuOptions.indexOf(menuChoice)<0){
System.out.print("Please enter a valid menu option: "+ menuChoice.indexOf(menuOptions));
menuChoice=kb.nextLine();
}
return menuChoice;
}
private void doWork(String option){
int choice = menuOptions.indexOf(option);
switch (choice) {
case 1: sayHello();
break;
case 2: doSomethingElse();
}
}
private void sayHello(){System.out.println("hello");}
private void doSomethingElse(){System.out.println("something Else");}
}