Best practice to create two-level deep selection menu in Java console - java

I'm about to create an application that runs off the java console as opposed to the GUI, and I had a question about the best way to approach displaying menus with another level of a submenu. I've quickly typed up the below code to sort of give you an idea of what I'm attempting to achieve.
I'm aiming for the menus of modify account and access account to both open up sub-menus with further choices. Essentially I'm trying to de-clutter the application from having too many choices (e.g. Change Account ID, Change Account Balance, Change Account Nickname, etc).
I've seen some places around the internet that seem to dislike this type of "tree-like" structure. Is there any clean way of doing something like this, or would I be forced to do something like create individual methods (i.e. AccountMenu) which would display different prompts and essentially create yet another do while loop.
public class Console
{
public static void main (String[] args) {
System.out.println("Welcome to the console application");
int selection =0;
do
{
System.out.println("[1] Create New Account");
System.out.println("[2] Modify Account");
System.out.println("[3] Access Account");
System.out.println("[4] Quit");
System.out.print("Insert selection: ");
selection = ReadConsole.nextInt();
switch (selection)
{
case 1: dothislater; break;
case 2: dothislater; break;
case 3: dothislater; break;
case 4: System.out.println("Application has been shut down")
break;
default:
System.out.println("The selection was invaild!");
}
}while (selection != 4);
}
}
I'm new to java, and I'm simply doing this to fool around with what it's like. Suggestions / ideas? I should also mention that I don't want to implement a "proper" GUI like swing elements.

You could make for every (sub)menu another function.
The reason why this aint prefered is because it aint in the spirit of OOP.
public class Console {
private int testint = 1;
/**
* #param args
*/
public static void main(String[] args) {
Console console = new Console();
console = console.mainMenu(console);
System.out.println("Application has been shut down");
}
private Console mainMenu(Console console) {
System.out.println("Welcome to the console application");
int selection = 0;
do {
System.out.println("[1] Create New Account");
System.out.println("[2] Modify Account");
System.out.println("[3] Access Account");
System.out.println("[4] Quit");
System.out.print("Insert selection: ");
// selection = testint++;
selection = ReadConsole.nextInt();
switch (selection) {
case 1: return console.submenu1(console);
case 2: return console.submenu1(console);
case 3: return console.submenu1(console);
case 4: return console;
default:
System.out.println("The selection was invalid!");
}
} while (selection != 4);
return console;
}
private Console submenu1(Console console) {
System.out.println("Welcome to the SUBMENU");
int selection = 0;
do {
System.out.println("[1] SUBMENU_1");
System.out.println("[2] SUBMENU_2");
System.out.println("[3] SUBMENU_3");
System.out.println("[4] Return");
System.out.print("Insert selection: ");
//selection = ++testint;
selection = ReadConsole.nextInt();
switch (selection) {
case 1: return console.submenu1(console);
case 2: return console.submenu1(console);
case 3: return console.submenu1(console);
case 4: return console.mainMenu(console);
default:
System.out.println("The selection was invalid!");
}
} while (selection != 4);
return console;
}
}
Might need a bit more tweaking, but you might get the idea

Related

Java Looping Meters Conversion Program

I cannot figure out how to have the program loop through the Conversion Menu and then return to the Main Menu from choice "4 Return" as shown in the example.
Example of what the program output might look like:
Main Menu
Enter Distance
Quit the program
Please enter your choice: 1
 
Enter a distance in meters: 500
 
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 1
500 meters is 0.5 kilometers
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 3
500 meters is 1640.5 feet
 
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 4
 
Main Menu
Enter Distance
Quit the program
Please enter your choice: 2
 
Good Bye!
I've found multiple solutions for the program when it doesn't include the main menu and the looping back to it but I can't seem to find anything on this.
Here's what I have:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int choice;
int option;
double meters = 0;
conversionControl();
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
break;
case 2:
quitProgram();
break;
default:
showError("Please Enter a Valid Option");
conversionControl();
option = keyboard.nextInt();
if (option == 1) {
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
}
else if ( option == 2) {
quitProgram();
}
break;
}
do{
menu();
choice = keyboard.nextInt();
switch (choice) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
conversionControl();
option = keyboard.nextInt();
if (option == 1) {
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
}
else if ( option == 2) {
quitProgram();
}
break;
default:
showError("Please Enter a Valid Option");
menu();
choice = keyboard.nextInt();
break;
}
} while(choice != 0); {
}
}
I guess I did figure my own way out but I keep thinking it isn't the correct way or there's an easier way. Plus, some errors occur when testing some inputs (mainly the the showError method calls will output either the incorrect menu or it will just close the program after so many wrong inputs).
Any help/constructive criticism would be greatly appreciated. I'm somewhat new to coding (know HTML) and new to to this site as well.
Thank you!
Bob
As it look like an exercise I won't give you a complete code, but a pseudo code to help you understand the strategy here.
To clarify, I'll name your first menu as mainMenu and the second as convMenu.
You have already implemented the good strategy for the convMenu. The idea is to make a loop, and exist only when the user tells you so. What you are missing is to do the same for the mainMenu and to think the convMenu as a sub-menu of the mainMenu. Which means when you are in the convMenu you are not outside of the mainMenu.
//That's pseudo code
do {
displayMainMenu();
readUserInput();
switch(userInput) {
case 1 :
//here you put your convMenu
do {
displayConvMenu();
readUserInput();
switch(userInput) {
case 1, 2, 3 :
doConvertion();
case 4 :
exitConvMenu = true;
default :
//wrong input display a message and loop
}
} while(!exitConvMenu)
case 2:
exitMainMenu = true;
default :
//wrong input display a message and loop
}
} while(!exitMainMenu)
Breaking down the code in little pieces usually makes it easier to understand and debug. Divide and conquer! Here is how I would do it:
First create a Menu class which represent a menu, it can print the Menu on screen and check that a choice is valid:
class Menu {
private String title;
private List<String> choices;
private String prompt;
public Menu(String title, List<String> choices, String prompt) {
this.title = title;
this.choices = choices;
this.prompt = prompt;
}
public boolean isChoiceAllowed(int i) {
return i > 0 && i <= choices.size();
}
public void show() {
System.out.println(title);
for(int i=0; i<choices.size(); i++) {
System.out.println(" " + (i+1) + ". " + choices.get(i));
}
System.out.println(prompt);
}
}
Then define your 2 menus:
private static final Menu mainMenu = new Menu(
"Main Menu",
Arrays.asList("Enter Distance", "Quit the program"),
"Please enter your choice");
private static final Menu conversionMenu = new Menu(
"Conversion Menu",
Arrays.asList("Convert to kilometers", "Convert to inches", "Convert to feet", "Return"),
"Please enter your choice");
Have a method to read the user input:
private static int readUserInput() {
int input = keyboard.nextInt();
// Check if input is valid, if not call back readUserInput() until a valid input is given
if(!currentMenu.isChoiceAllowed(input)) {
System.out.println("Please Enter a valid option");
return readUserInput();
}
return input;
}
Have a method to handle choices in the Main Menu
private static void handleMainMenuChoice(int choice) {
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
// Set the current menu to be the Conversion Menu
currentMenu = conversionMenu;
break;
case 2:
quitProgram();
break;
}
}
Have a method to handle choices in the Conversion Menu
private static void handleConversionMenuChoice(int choice) {
switch (choice) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
// Set the current menu to be the Main Menu
currentMenu = mainMenu;
break;
}
}
Have a method to handle the user choice and dispatch it to the appropriate method above:
private static void handleChoice(int choice) {
if(currentMenu == mainMenu) {
handleMainMenuChoice(choice);
} else {
handleConversionMenuChoice(choice);
}
}
Then tie it up together:
private static double meters;
private static Menu currentMenu;
private static Scanner keyboard = new Scanner(System.in);
<Insert menu definitions here>
public static void main(String[] args) {
currentMenu = mainMenu;
int choice;
while (true) {
// Show the current menu
currentMenu.show();
// Read the user input
choice = readUserInput();
// Handle the user choice
handleChoice(choice);
}
}
public static void main(String[] args) {
int choice = 0;
int option;
double meters = 0;
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while(!exit) {
System.out.println("\nEnter your choice :Enter Distance.. click1\r\n" +
"\r\n" +
"Quit the program.. click2");
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
System.out.println("Conversion Menu\r\n" +
"\r\n" +
"Convert to kilometers .. click1\r\n" +
"\r\n" +
"Convert to inches .. click2\r\n" +
"\r\n" +
"Convert to feet .. click3\r\n" +
"\r\n" +
"Return.... .. click4");
int choice1 = keyboard.nextInt();
switch(choice1) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
exit = true;
break;
}
break;
case 2:
exit = true;
break;
default:
break;
}
}
}

Repeating for loop in menu

I'm trying to create a hotel menu in Java (I'm still learning the language) and I've run into an issue. I can make the menu open a new menu, but when I make a choice from that second menu, it constantly loops. I think it's the for loop that is causing the issue. Can anyone advise how I get the second menu entry to stop looping? Methods below:
Menu class method:
public void getMenu()
{
Floor floor = new Floor();
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Booking Menu");
System.out.println("Select from the options below");
System.out.println("1. Check room availability");
System.out.println("2. Display floor");
System.out.println("3. Display all availability");
System.out.println("4. Cancel Booking");
System.out.println("Please enter choice (press 8 to continue)");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: room.getRoomMenu();
break;
case 2:
break;
case 3:
break;
}
}
while (choice !=8);
}
That menu opens a second menu in this method:
public void getRoomMenu()
{
Floor f1 = new Floor(1);
Floor f2 = new Floor(2);
Floor f3 = new Floor(3);
Floor f4 = new Floor(4);
boolean check = false;
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Which Floor?");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: f1.displayFloor();
break;
case 2: f2.displayFloor();
break;
case 3: f3.displayFloor();
break;
case 4: f4.displayFloor();
break;
}
}
while(choice !=8);
kboard.close();
}
The second menu option should display the chosen floor which displays all rooms on that floor. This is the displayFloor method:
public void displayFloor()
{
/**
* Displays floor number and room display method
*/
System.out.println("Floor: "+floorNumber);
for(int counter=0;counter<rooms.length;counter++)
{
rooms[counter].display();
}
}
Both your while loops continue looping as long as choice != 8. And since you never modify the choice inside the loop, it will just continue looping (unless 8 was input by the user).
Also note that the break; you added are breaks for the switch-case, not to stop the do-while-loop. To have a break within the switch-case stop the entire do-while-loop, you should use a label to give the loop a name, and break that one. In addition, you should ask the user to give a new input if it didn't came into one of the switch-cases, otherwise it will still loop forever. So something like this:
choice = kboard.nextInt();
myLoop: do {
switch(choice) {
case 1:
f1.displayFloor();
break myLoop;
case 2:
f2.displayFloor();
break myLoop;
case 3:
f3.displayFloor();
break myLoop;
case 4:
f4.displayFloor();
break myLoop;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
choice = kboard.nextInt(); // Ask the user for a new input
break; // <- This break only breaks the switch, not the loop
}
} while(choice !=8);
If your intention was to continue looping until the user input 8, it should be something like this instead:
choice = kboard.nextInt();
do {
switch(choice) {
case 1:
f1.displayFloor();
break;
case 2:
f2.displayFloor();
break;
case 3:
f3.displayFloor();
break;
case 4:
f4.displayFloor();
break;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
}
choice = kboard.nextInt(); // Ask the user for a new input for the next iteration
} while(choice !=8);
The loop is occurring here:
while(choice !=8);
You need to make sure that the ending condition is always satisfied at some point to avoid unwanted infinite loops.
Maybe you meant if(choice != 8) rather than a do/while loop (which will keep running until choice is 8, which will only occur if the user inputs 8).

How to create a menu console loop?

I have to create a menu for the user to select from and I need it to loop when the user inputs the incorrect option. The code that I have so far; it will either loop continually or when I run the program it, gives me the outputs for all the selections instead of for the one I specifically entered. The loop I have is a do / while loop with a switch statement. I'll paste what I've tried below. I just need to know if my code for the loop is correct and if not how do I fix it? If any clarifications are needed, just ask. I apologize if I sound really lazy or stupid, I just want to be able to understand this and at times, I just don't, so just look for a little extra help.
do
{
int selection = 0;
System.out.println("Please choose one of the following to determine whether you are a new or existing cutomer:");
System.out.println("[1]- Existing Customer");
System.out.println("[2] - New Customer");
System.out.println("Insert selection:");
switch (selection)
{
case 1:
System.out.println("Welcome Back" + userName);
break;
case 2:
System.out.println("Hello, I see you are a new customer,");
System.out.println("let's get your account setup!");
break;
case 3:
default: System.out.println("That is not a vaild. Please select from one of the following options.");
break;
}
while (selection !=3);
String[] options = new String[]{
"Existing Customer",
"New Customer"
};
int selection = 0;
do{
System.out.println("Please choose one of the following to determine whether you are a new or existing customer");
for (int i = 0; i < options.length; i++) {
System.out.printf("[%s] - %s%n",i+1, options[i]);
}
String input = new Scanner(System.in).nextLine();
try{
selection = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println("That is not a vaild. Please select from one of the following options.");
selection = 0;
}
}while(selection <= 0 || selection > options.length);
switch(selection){
case 1:
System.out.println("Welcome Back");
break;
case 2:
System.out.println("Hello, I see you are a new customer,");
System.out.println("let's get your account setup!");
break;
}

Switch Statement not exiting loop. (Java)

I have a simple menu system set up where the user hits 8 to leave. However for some reason when i hit 8 during testing it simply goes back to the top of the loop like nothing happened.
package potluck;
import java.util.*;
import potluck.*;
public class Controller {
private Scanner input;
private final static int USER_LOGIN = 0;
private final static int CREATE_MEMBER = 1;
private final static int CREATE_ADMIN = 2;
private final static int CREATE_RECIPE = 3;
private final static int COMMENT = 4;
private final static int DELETE_RECIPE = 5;
private final static int EXIT = 8;
public Controller(){
input = new Scanner(System.in);
startUp();//no better name to be thought of
}
public void startUp() {
// TODO Auto-generated method stub
int choice;
do {
this.displayMenu();
choice = input.nextInt();
input.nextLine();// clears carriage return
//depending on choice takes to a different menu
switch (choice) {
case CREATE_MEMBER:
Member member = new Member();
break;
// case CREATE_ADMIN:
// member.addAdmin();
// break;
case CREATE_RECIPE:
Recipe.addRecipe();
break;
case COMMENT:
Recipe.addComment();
break;
case DELETE_RECIPE:
Recipe.deleteRecipe();
break;
case EXIT:
System.out.println("Thanks for using our software");
break;
default:
System.out.println("Error, Invalid selection.");
}
} while (choice != 8); //choice 8 exits
}
private void displayMenu() {
System.out.println("1 Create Member");
System.out.println("2 Create Admin Member");
System.out.println("3 Create Recipe");
System.out.println("4 Leave Comment");
System.out.println("5 Delete Recipe");
System.out.println("8 Exit");
System.out.println("Please enter menu option, to exit enter 8");
}
}
In testing it claims that choice is 8, which should break the do while...but doesn't...
UPDATE: When copying over code, I left in some work around that i was told not to use. I had system.exit in there under choice 8, but was told that's bad code
Sorry everyone. I'm an idiot. In the main where I launch this, I had instantiated a new controller (which is the class you're looking at) which in the constructor launches the menu. Then i called the startup() method. Which means that it was working perfectly, it was just running twice because i'm dumb.
public static void main(String[] args) {
// TODO Auto-generated method stub
Controller cntlr = new Controller();
cntlr.startUp();
}
public Controller(){
input = new Scanner(System.in);
startUp();//no better name to be thought of
}
public void startUp() {
// TODO Auto-generated method stub
int choice;
do {
this.displayMenu();
choice = input.nextInt();
input.nextLine();// clears carriage return
//depending on choice takes to a different menu
switch (choice) {
case CREATE_MEMBER:
Member member = new Member();
break;
case CREATE_ADMIN:
member.addAdmin();
break;
case CREATE_RECIPE:
Recipe.addRecipe();
break;
case COMMENT:
Recipe.addComment();
break;
case DELETE_RECIPE:
Recipe.deleteRecipe();
break;
case EXIT:
System.out.println("Thanks for using our software");
break;
default:
System.out.println("Error, Invalid selection.");
}
} while (choice != 8); //choice 8 exits
}
private void displayMenu() {
System.out.println("1 Create Member");
System.out.println("2 Create Admin Member");
System.out.println("3 Create Recipe");
System.out.println("4 Leave Comment");
System.out.println("5 Delete Recipe");
System.out.println("8 Exit");
System.out.println("Please enter menu option, to exit enter 8");
}
}
TL;DR. I'm dumb, and constructors are a thing I should pay more attention to.

Switch statement loops through

I'm trying to make a simple Menu with the switch statement. However i'm having a problem with the switch:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException{
char selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char)System.in.read();
switch(selection){
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
}
}
while(selection != '3');
}
}
For some reason, when selecting either one or two, the result is that print menu gets printed twice, like this:
Program output:
Choose option:
1. opt1.
2. opt2.
3. opt3.
1
opt1 chosen
Choose option:
1. opt1.
2. opt2.
3. opt3.
Choose option:
1. opt1.
2. opt2.
3. opt3.
The question is, what causes this problem?
When you press a number and <Enter> this is two characters not one. i.e. you are typing
1\n
This is unavoidable, but you can chose to parse the input differently with Scanner which handles this differently, or you can ignore it. (or you can expect the user must type a \n after a number...
As Peter pointed out, the problem arises because of the way you are reading the 'selection' input. You can correct the functionality as follows:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException {
char selection = '0';
while (selection != '3') {
if (selection != '\n') {
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
}
selection = (char) System.in.read();
switch (selection) {
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
default:
break;
}
}
}
}
Peter Lawrey is right
I'm suggest using Scanner class :
public static void printMenu() throws IOException {
Scanner scanner = new Scanner(System.in);
int selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char) scanner.nextInt();
switch(selection){
case 1:
System.out.printf("opt1 chosen\n");
break;
case 2:
System.out.printf("opt2 chosen\n");
break;
case 3:
break;
}
scanner.nextLine();
}
while(selection != '3');
}

Categories