How to create a menu console loop? - java

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;
}

Related

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).

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

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

How to stop the method continuously looping

I am currently trying to complete a program with multiple classes in java that will allow the user to input information to help him or her book tickets, accommodation, parking, etc for a rock festival. I have started with one of the classes 'accommodation' to return the correct input of the user to the main class, however, I have found when I run the program and enter option 3, it immediately loops continuously which I have to terminate. I have searched online for a way to stop the loop, and for it to return the correct inputted information to no avail, I would appreciate any help to a very new new noob, before this loop turns me loopy!
Below is my main class and the class 'accommodation'. thank you in advance and apologies for any messy coding I have, as I have been trying various options as I have said before.
import java.util.Scanner;
import java.util.InputMismatchException;
public class clydeRockfest {
public static void main(String[] args) {
boolean quit = false;
Scanner in = new Scanner(System.in);
int choice; // Display the menu
int answer = 0;
Accommodation accommodation = new Accommodation();
//accommodation.getaccommodation();
do{
System.out.println("1\t Festgoers");
System.out.println("2\t Ticket");
System.out.println("3\t Accommodation");
System.out.println("4\t Transport");
System.out.println("5\t Parking");
System.out.println("0\t Quit");
System.out.println("Please enter your choice:");
//Get user's choice
choice=in.nextInt();
if(choice == 0)
quit=true;
//Display the title of the chosen module
switch (choice) {
break;
case 3: accommodation.getaccommodation();
System.out.println("You require " + answer + " accommodation.");
break;
case 0:
quit=true;
break;
default: System.out.println("Invalid choice, please choose again.");
} //end of switch
} //end of the main method
while(!quit);
} //end of class
}
public class Accommodation {
private String accommodation;
void getaccommodation(){
int no = 0; // no accommodation at all required
int self_Pitch = 0; // chosen if requiring a pitch
int tent = 0; // chosen if using a tent
int answer = 0;
int choice = 0;
boolean done = false;
System.out.println("Do you require accommodation?");
System.out.println();
// Answer validation loop
boolean validanswer = true;
while (!validanswer){
System.out.println("Enter:(1=NO, 2=SELF-PITCH, 3=TENT)");
System.out.println();
if(answer > 0 && answer < 4){
validanswer = true;
done = true;
}// ends if
else{
System.out.println();
System.out.println("That is not a valid answer, please choose again:");
System.out.println();
} // ends else
} //ends while
}
public void setaccommodation(String accommodation){
this.accommodation = accommodation;
}
Output:
Please enter your choice:
3
Do you require accommodation?
You require 0 accommodation.
1 Festgoers
2 Ticket
3 Accommodation
4 Transport
5 Parking
0 Quit
Please enter your choice:
you prime your loop by setting done=false but never set done = true so your loop will never end
You have two loops checking if user is done, and the condition of the first one (with the done) variable is never changed. Just remove this loop, and you should be fine.
Also, it looks like the condition for the second loop variable should be
if (answer > 0 && answer < 4)
to match your menu alternatives.
You never set done to true. It seems you may need to do it here:
if(answer >=0 && answer <=4){
validanswer = true;
done = true;
}
else{
//code
}
However, I'm not even sure you need that outer loop in the first place:
while(!done){
It seems redundant.

JAVA: Creating a Menu Loop

My program contains a few options that the user can select via the input of a number which allows them to complete a specific task. Currently, my code is set up with if and else if loops to complete task if a certain number of input. However, at the minute the program terminates after one task. I want the user to be able to input another number to complete another task. I have tried surrounding the code with a while loop and an exit option to allow the user to escape the loop and end the program, but this is not working and results in a "java.util.NoSuchElementException". The program works fine without the while loop.
This is an example of the current code which hopefully conveys what I mean:
System.out.println("Enter one of the following commands:");
System.out.println("1 - something..");
System.out.println("2 - something else..");
System.out.println("3 - exit");
Scanner scanchoice = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\"");
int choiceentry = scanchoice.nextInt();
while (choiceentry != 3) {
if (choiceentry < 1 || choiceentry > 3) {
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
choiceentry = scanchoice.nextInt();
}
else if(choiceentry == 1) {
// ..do something
}
else if(choiceentry == 2) {
//..something else
}
else if(choiceentry == 3) {
//...exit program
}
}
So I want to get into this loop, and only exit to terminate the program. I'm hoping that the while loop would take the user back to a menu, allowing you to select another option, however this is not working. What is wrong with this code? And how can I implement this idea?
Thanks in advance!
Use Scanner#hasNextInt() before you call Scanner.nextInt() to get rid of the NoSuchElementException
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
hasNextInt() returns true only if the next token is a valid int
You can do like this
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
}
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
I have changed it to use switch statements, since they come handy in getting input data
You are only asking the user to pick another menu item if choice is < 1 or > 3
you have to set this code in an else statement`:
while (choiceentry != 3) {
else if(choiceentry == 1) {
// ..do something
}
else if(choiceentry == 2) {
//..something else
}
else if(choiceentry == 3) {
//...exit program
}
else{
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
choiceentry = scanchoice.nextInt();
}
}
If you want your program to continue prompting the user to select a task you'll need to move that prompt as well as your nextInt() call to somewhere inside your loop yet outside of an if statement so that it will always be invoked on each iteration.
As Mr Phi suggested in the comments, a switch statement would be a better alternative to your current if-else structure. It'll make your code cleaner to read and a default case is pretty nice for catching unexpected values.
I'd also add that a do-while might be more suitable for this task. This way you won't need to code your prompt for a choice twice.
int choiceentry;
do {
System.out.println("Enter \"1\", \"2\" or \"3\"");
choiceentry = scanchoice.nextInt();
switch (choiceentry)
{
case 1:
// do something
break;
case 2:
// ..something else
break;
case 3:
// .. exit program
break;
default:
System.out.println("Choice must be a value between 1 and 3.");
}
} while (choiceentry != 3);

Having trouble with user input validation

This is a small part of my program that I am working on. I'm trying to check if the user enters the correct number.
They have five choices to choose from so they can either hit 1, 2, 3, 4, or 5. Then press enter.
So I want to check to make sure the user doesn't type anything in < 1 or > 5. I got that part to work... But I just want to know if there is a easier way to do it then from what I did in code below.
The next part is that I also want to make sure the user doesn't type in letters. like "gfgfadggdagdsg" for a choice.
Here is my code of the part I am working on....
public void businessAccount()
{
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
if (selection > 5){
System.out.println("Invalid choice.");
businessAccount();
}
else if (selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}
else {
switch(selection)
{
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
}
You may get rid of checking < 1 and > 5 by adding a default case.
try{
selection = input.nextInt();
switch(selection){
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
break;
default:
System.out.println("Invalid choice.");
businessAccount();
}
}catch(InputMismatchException e){
//do whatever you wanted to do in case input is not an int
}
Using BufferedReader you can do something like this:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int selection = 0;
try{
selection = Integer.parseInt(s);
if(selection > 5 || selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}else{
// your switch code here
}
// you can use #Nishant's switch code here. it is obviously better: using switch's default case.
}catch(NumberFormatException ex){
// throw new Exception("This is invalid input"); // or something like that..
System.out.println("Invalid choice.");
businessAccount();
}
Hope that helps.
Note: you must import java.lang.NumberFormatException import java.io.InputStreamReader and import java.io.BufferedReader
Use the switch case it's better and more speed the if statement when you check selection from a Specific.
an alternative would to use regular expressions to get it work.
Say you have a string x then
String x = "something";
if(x.matches("regex")){
}
Another way to do this is surround with try catch.

Categories