| RHS => Allan => Basic Programming => Exercises => Menu |
Updated:
02/02/2004 23:36 WebMaster: allanhn@rhs.dk |
Menu
The problem
Often we need to give the user of a program some choices to choose from - a
menu.
Let's look at how the user will experience a menu:
When the program is executed, the following is shown on the screen:
![]() |
If key 1 is typed, the user will see the following:
![]() |
Then the menu is repeated again.
Similar for choosing 2, 3 or 4.
If 9 is typed, the program ends.
If any other key is typed the user will see an error message.
Then the menu is repeated again.
Question 1 Worker
class
You are to develop a program, which can accomplish the mission described
above.
For this we need a model class (worker class) Menu,
which must have 5 methods:
runMenu,
menuChoice1,
menuChoice2, menuChoice3 and
menuChoice4.
runMenu will be the method
that displays the menu.
The other four methods will be the methods that perform the actual
work - there is one method
for each choice from the menu (except for choice 9 which just ends the program). For
this simple version we just show a message-dialog box (like the one above).
Only runMenu and menuChoice1 will
be described in
the following.
Create the class Menu.
From the JOptionPane you'll get the answer from
the user as a String (let's
call it answer).
From this String you should
subtract the first letter
an store it in a char variable
- ch.
The runMenu method should then resemble the following template:
public static void runMenu() {
while (ch != '9') {
answer = JOptionPane.showInputDialog(MENU_TEXT);
ch = answer.charAt(0);
switch(ch) {
case '1' : menuChoice1(); break;
// fill in other values - do it yourself...
case '9' : JOptionPane.showMessageDialog(null, "Goodbye...");
break;
default : JOptionPane.showMessageDialog(null, ch + " not valid choice!");
}//switch
}//while
}//runMenu()
The constant, MENU_TEXT, holding the text of the menu should be something like:
private static final String MENU_TEXT =
"\n" +
" 1: Create\n\n" +
//fill in the rest yourself!
" 9: Exit\n\n" +
" Enter your choice (1-4, 9): ";
The method menuChoice1 should be something like:
private static void menuChoice1() {
JOptionPane.showMessageDialog(null, "You chose 1");
}
Create the other methods in a similar way. Compile and save.
Question 2 Application
class
Make the MenuApp class with the main method.
public class MenuApp {
public static void main(String[] args) {
Menu menu = new Menu();
menu.runMenu();
//make DOS-window active
System.exit(0);
}//main(String[])
}//MenuApp
Save this program, compile and run.
Later we'll extend this program so something useful is actually done when the user makes a choice.