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).
Related
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;
}
I know about the return statement and have tried it. System.exit(0) also does the same. But using it here terminates the program. Is there any way i can use so that if the user types other input except 1-7 , the program doesn't terminate , so that i don't have to recompile and rerun the program ? Or is it not possible in Java ?
import java.util.Scanner;
public class NewShoppingCart{
public static void main(String args[]) {
boolean flag = true;
long code;
String choice;
NewShop aShop = new NewShop();
Scanner sc = new Scanner(System.in);
Integer parse = 0;
System.out.println("-----ITEM------");
do {
System.out.println("1. Display all items");
System.out.println("2. Search items");
System.out.println("3. Add items to list");
System.out.println("4. Add items to cart");
System.out.println("5. Display cart");
System.out.println("6. Issue item");
System.out.println("7. Exit");
System.out.println("Choice:");
choice = sc.nextLine();
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
}
while (flag != false);
sc.close();
}
}
Change this
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
to
catch(Exception e){
System.out.println("Please enter a valid integer");
continue;
}
also in your else block have continue instead of return.
You can never go out of main with just one thread. This is likely an XY problem. What you really want is to go back to the start of the loop if the user inputs something invalid.
The continue keyword will stop executing the current iteration of the enclosing loop and start a new iteration immediately. This is what you should use in place of return.
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return; // <--- change this to "continue;"
}
Also, this:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
should really be:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
}
}
else {
System.out.println("Please enter choice relevant to context");
continue;
}
The "Please enter choice relevant to context" message should really be printed in the else statement. Because in your if, you already checked whether parse is between 1 and 7, so in the switch, parse can't be anything else so the default branch is never reached. After you print the message, you continue; in order to go back to the start of the loop.
So I need the statements inside the while loop to repeat until the user enters 4 (which exits the program), but when I try to run the program, nothing is outputted to the screen (but it compiles just fine). Why would it do this? This answer is probably really simple, but any help would be really appreciated!
public class Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int answer;
boolean bool = true;
while(bool);
{
System.out.println("\n\tGeometry Calculator\n" +
"\t1. Calculate the Area of a Circle\n" +
"\t2. Calculate the Area of a Rectangle\n" +
"\t3. Calculate the Area of a Triangle\n" +
"\t4. Quit\n");
System.out.print("\tEnter your choice (1-4): ");
answer = keyboard.nextInt();
switch(answer)
{
case 1:
System.out.println("\n\tCalculating the area of a circle...");
break;
case 2:
System.out.println("\n\tCalculating the area of a rectangle...");
break;
case 3:
System.out.println("\n\tCalculating the area of a triangle...");
break;
case 4:
System.out.println("\n\tQuiting...");
System.exit(0);
break;
default:
System.out.println("\n\tPlease enter a number between 1 and 4.");
}
if(answer == 4)
bool = false;
}
}
You have one tiny mistake. You have added ; after the while loop. Just delete it. Your code should be
while(bool)
I am new to switch loops and am having multiple problems with this currency converter program I am trying to create.
First, I would like to loop the case 1 where the user keeps entering values until they type -1 so it stops and moves on. At the moment, it does not do this. Once I've entered the GPR values on switch 1 and then loop back to the menu keeping the original GPR stored values.
Code is here:
import java.util.Scanner;
public class Conversion {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int Choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
Choice = input.nextInt();
switch (Choice) {
case 1:
while (!exchange.equals("-1"));{
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange (Type '-1' to stop) ");
}
case 2:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in euros are" + poundDollars);
case 3:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in euros are" + poundYen);
case 4:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in euros are" + poundRupees);
case 5:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in euros are" + poundEuro);
case 6:
break;
}
input.close();
exchange.close();
}
}
switch is not a loop. It's a branching statement like if. It has break, but that is only present because you can "fall through" to the next case statements. Currently you are falling through on most of them, because you've forgot putting in the break statements between the cases.
A switch statement isn't a loop. Consider it a replacement for a series of else-if statements. Your code actually reads more like this:
if(Choice == 1)
{
}
else if(Choice == 2)
{
}
else if(Choice == 3)
{
}
else if(Choice == 4)
{
}
else if(Choice == 5)
{
}
else if(Choice == 5)
{
}
However, your switch cases should be terminated with break statements. If one is not, unlike the else-ifs above, execution will fall-through to the next case and execute the code in that one too, until it finally reaches a break statement or goes through all the cases.
What you want is for your while-loop to wrap AROUND your switch statement, but you should fix your while-loop first, since you terminated it with a semicolon, it is infinite. While-loops don't need a semicolon at the end, unless you do not have a body for it but you do have some side-effect happening in the conditional check that will eventually cause it to end.
while( blah )
{
switch( blah )
{
case 1:
// Do stuff for this case
break;
case 2:
// Do stuff for this case
break;
default:
// Do stuff when no case is matched
break;
}
}
I think you're a bit confused. As noted by immibis in his comment, switch statements are not loops, so you need to enclose the switch statement inside a loop.
Then, you're missing the break statements at the end of each case. Quoting the Java tutorials:
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Your program should be something like this:
public static void main(String[] args) {
// Variable definitions
while(true) { // This is a little trick to force the application to repeat
// a task until you explicitly break the loop
// Code to print your menu
choice = input.nextInt();
if(choice == -1 || choice == 6)
break; // Break the while loop if choice is -1 or 6
switch(choice){
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
If you don't put those break statements at the end of each case block, your program will fall through every option.
Please read:
The Java tutorials: The switch statement
The Java tutorials: The while statement
Another option would be something like this:
public static void main(String[] args) {
// Variable definitions
/*
Now let's use a labeled loop
*/
menu: while(true) {
// Code to print your menu
choice = input.nextInt();
switch(choice){
case -1: // Nothing goes here, so the execution will fall through
// to the next case
case 6:
break menu; // This will break the menu loop.
// Since the previous case simply falls through to
// this one, this will happen if choice is
// either -1 or 6
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
More reading:
The Java tutorials: Branching statements
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.