Java Looping Meters Conversion Program - java

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

Related

Basic Menu with Cases

I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.

How do I go back to my previous menu?

I've looked at everything mentioned about this and if I make a do/while loop it will just repeat the selection. If I make them conditionals instead of a switch it gives me "NoSuchElementException: No line found". Now its also giving me a "NoSuchElementException: No line found" even though I am back to a switch. I just want to know what I'm missing in this code that will let the user back out their first selection (while loop) to make a different one. Here is the code:
public class Zoo {
static FileRead fr = new FileRead();
private static final Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
while (userChoice == 1) {
// Select Animal
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
userChoice = menu();
break;
} FileRead.readAnimal(Name);
}
while (userChoice == 2) {
// Select Habitat
int animal = habitatSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Habitat - Penguin";
break;
case 2:
Name = "Habitat - Bird";
break;
case 3:
Name = "Habitat - Aquarium";
break;
default:
userChoice = menu();
break;
}
FileRead.readHabitat(Name);
}
// Exit Program
if (userChoice == 3) {
System.out.println("Thank you!");
System.exit(0);
}
// Error for invalid option
else {
System.out.println("ERROR: Invalid Selection");
}
}
}
private static int habitatSelect() {
// Habitat Menu
System.out.println("Which habitat would you like to monitor?");
System.out.println("1. Penguin Habitat");
System.out.println("2. Bird Habitat");
System.out.println("3. Aquarium");
System.out.println("4. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int animalSelect() {
// Animal Menu
System.out.println("Which animal would you like to monitor?");
System.out.println("1. Lion");
System.out.println("2. Tiger");
System.out.println("3. Bear");
System.out.println("4. Giraffe");
System.out.println("5. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int menu() {
// Main Menu
System.out.println("WELCOME! Plese choose from the following");
System.out.println("1. Monitor Animal");
System.out.println("2. Monitor Habitat");
System.out.println("3. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
}
This all reads a from another file in the package. If that code is needed I will also post it.
Tweak your main method as below
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
switch (userChoice) {
case 1: // only for animals
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (Name != null) // read file only if selection is correct
FileReader.readAnimal(Name);
break;
case 2: // only for habitat
int habitat = habitatSelect();
String habitatName = null;
switch (habitat) {
case 1:
habitatName = "Habitat - Penguin";
break;
case 2:
habitatName = "Habitat - Bird";
break;
case 3:
habitatName = "Habitat - Aquarium";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (habitatName != null) // read file only if selection is correct
FileRead.readHabitat(habitatName);
break;
case 3 : // only for exit
System.out.println("Thank you!");
System.exit(0);
default:
System.out.println("ERROR: Invalid Selection");
}
}
}
Thus after each sub-menu, the user is returned to the main menu. As for your exception, for now I have added a null check so that the file is read only if the selection is correct.
Also, note that the above code doesn't contain nested loop which increases the performance and also excludes (the slightly messy) recursive call.

program terminate after using try catch block in switch statement

the following code terminate after try catch block catches exception.its not allowing me to make choice from the menu option. so my question is what changes do i have to make on this code so that i can loop back so that i can get user input again.
public class Main {
public static void main(String[] args) {
Modify modifyObj = new Modify();
int choice = 0 ;
Scanner input = new Scanner(System.in);
//begin loop
do {
try{
//display menu
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
choice = input.nextInt(); //gets user input
switch (choice) {
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
}// end of switch statement
break;
}//end oftry
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
continue;
}
}while (choice!=0); //loop until user exit 0.
}//end of main
}// end of Main class
Make sure choice isn't 0 before you continue;
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
choice = 1; // <-- not 0.
continue;
}
Note that you default choice to an initial value of 0.
You Could Use Methods
If you extracted your logic into one (or two) utility methods to display the menu and get the user's choice it would simplify things; something like
private static void showMenu() {
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
}
private static int getUserOption(Scanner input) {
while (true) {
showMenu();
if (input.hasNextInt()) {
int t = input.nextInt();
switch(t) {
case 0: case 1: case 2: case 3:
return t;
}
} else {
input.nextLine();
}
}
}
Then your main could invoke it like
public static void main(String[] args) {
Modify modifyObj = new Modify();
Scanner input = new Scanner(System.in);
int choice;
// begin loop
do {
choice = getUserOption(input);
if (choice != 0) {
System.out.printf("You chose %d.%n", choice);
}
} while (choice != 0); // loop until user enters 0.
}// end of main

How to write a go back code so after the user selects a case he/she can go back to the last option?

package thecashmachin;
import java.util.Scanner;
public class TheCashMachin {
public static void main(String[] args) {
int pin, proceed2=0, withdraw, dailydraw, Proceed, proceed3 = 0;
double balance;
Scanner pinnumber = new Scanner(System.in);
Scanner proc2 = new Scanner(System.in);
Scanner withd = new Scanner(System.in);
Scanner Next = new Scanner(System.in);
Scanner proc3 = new Scanner(System.in);
balance = 9999.99;
dailydraw = 1000;
System.out.println(
"text .");
System.out.println("1)Proceed");
System.out.println("2)Return Card");
Proceed = Next.nextInt();
switch (Proceed) {
case 1:// Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin = new Scanner(System.in);
int Pincode = Pin.nextInt();
if (Pincode > 9999 && Pincode < 99999) {
System.out.println("1)Display Balance");
System.out.println("2)Withdraw Cash");
System.out.println("3)Other services");
proceed2 = proc2.nextInt();
} else {
System.err.println(
"text");
}
break;
case 2:// Return Card
System.err.println("text");
break;
default:
System.err.println(
"text");
break;}
switch (proceed2) {
case 1:
System.out.println("Your balance today is: 9999.99");
/*
* so right here the balance is shown and in real life you would have a go back button to display the other options but on my code after the balance is displayed you cant do anything else have to re run the the script i want a code that if selected goes back to the last option*/
break;
case 2:
System.out.println("Amount to withdraw");
withdraw = withd.nextInt();
System.out.println("Please take the cash");
System.out.println("Current Balance" + " " + (balance - withdraw));
System.out.println("Daily withdraw left:" + (dailydraw - withdraw));
if (withdraw > dailydraw) {
System.err.println("text");
}
case 3:
System.out.println("Would you like to;");
System.out.println("1)Order a check");
System.out.println("2)Order a Statement");
proceed3 = proc3.nextInt();
break;
default:
System.out.println("text");
}
switch (proceed3) {
case 1:
System.out.println("Your check has been orderd");
break;
case 2:
System.out.println("Your Statement has been orderd");
break;
}
}
}
DO
BOOLEAN = TRUE;
SWITCH() // WITH THE DIFFERENT CASES
DEFAULT BOOLEAN = FALSE;
WHILE BOOLEAN IS FALSE;
This should do. Use a simple do while loop.
Before entering the switch, your boolean is set to TRUE and if it comes to the default it turns it to FALSE and you loop until the boolean stays TRUE
An easy way I know is just making a Boolean before which is kept same as default..
boolean test = True;
while (test)
{
switch(Proceed)
{
case 1://Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin=new Scanner(System.in);
int Pincode=Pin.nextInt();
test = false;
break;
case 2://Return Card
System.err.println("Your card is being ejected.\n Please Wait..");
test = false;
break;
default:
System.err.println("Sorry your request could not be processed.\n Please enter the pin again.\n")
// when neither case is true, keeps loop running.
break;
}
}

Why can I not use 2 switch statments in java

So I am trying to write a program to order items.
I must use switch statements to do this but the problem I am having is if I use the switch statement if I try to use a second switch after it also gets called during the first
And even asking for other input after the switch statement should be finished it seems to not call them correctly.
The code I tried is this
public static void main(String[] args) {
int menu = 0;
int seldelivery = 0;
double delivery = 0;
double selection = 0;
String name;
String student;
String mobile;
Scanner reader = new Scanner (System.in);
System.out.println("Please select\n1:Coffee\n2:Tea\n3:Quit");
menu = reader.nextInt();
switch (menu){
case 1:
System.out.println("1 Cappucino €2.00\n2 Latte €2.00\n3 Espresso €1.50\n4 Americano €1.70");
menu = reader.nextInt();
if (menu == 1) {
selection = 2.00;
System.out.println("You have selected Cappucino");
} else if (menu == 2) {
selection = 2.00;
System.out.println("You have selected Latte");
} else if (menu == 3) {
selection = 1.50;
System.out.println("You have selected Espresso");
} else if (menu == 4) {
selection = 1.70;
System.out.println("You have selected Americano");
} else {
System.out.println("inavlid selection please try again");
}
break;
case 2:
System.out.println("1.Bewley’s Breakfast Tea (Pot for €1.80)\n2.Peppermint €1.50\n3 Camomile €1.50");
menu = reader.nextInt();
if (menu == 1) {
selection = 1.80;
System.out.println("You have selected Bewley’s Breakfast Tea");
} else if (menu == 2) {
selection = 1.50;
System.out.println("You have selected Peppermint");
} else if (menu == 3) {
selection = 1.50;
System.out.println("Camomile");
} else {
System.out.println("Invalid selection");
}
break;
case 3: //exit
System.exit(0);
default:
System.out.println("Invalid selection");
break;
}
System.out.println("Please choose one of the following");
System.out.println("1 Delivery €1.00 extra");
System.out.println("2 Pickup at canteen");
delivery = reader.nextInt();
switch (seldelivery) {
case 4:
System.out.println("1 Delivery will add €1.00");
break;
case 5:
System.out.println("2 Please head to the canteen to collect your order");
break;
default:
System.out.println("Invalid selection");
break;
}
System.out.println("Please enter your full name including your middle name");
name = reader.nextLine();
System.out.println("Please enter your student number");
student = reader.nextLine();
System.out.println("Please enter your phone number");
mobile = reader.nextLine();
}
}
I tried writing the code like this instead:
public static void main(String[] args) {
int menu = 0;
int menu1;
double delivery = 0;
double selection = 0;
String name;
String student;
String mobile;
Scanner reader = new Scanner(System.in);
System.out.println("Please select\n1:Coffee\n2:Tea\n3:Quit");
menu = reader.nextInt();
switch (menu) {
case 1:
System.out.println("1 Cappucino €2.00\n2 Latte €2.00\n3 Espresso €1.50\n4 Americano €1.70");
menu = reader.nextInt();
if (menu == 1) {
selection = 2.00;
System.out.println("You have selected Cappucino");
} else if (menu == 2) {
selection = 2.00;
System.out.println("You have selected Latte");
} else if (menu == 3) {
selection = 1.50;
System.out.println("You have selected Espresso");
} else if (menu == 4) {
selection = 1.70;
System.out.println("You have selected Americano");
} else {
System.out.println("inavlid selection please try again");
menu = reader.nextInt();
}
System.out.println("Please choose one of the following\n1 Delivery €1.00 extra\n2 Pickup at canteen");
menu1 = reader.nextInt();
switch (menu1) {
case 1:
System.out.println("1 Delivery will add €1.00");
if (menu1 == 1) {
delivery = 1.00;
System.out.println("You have selected to have your order delivered");
}
break;
case 2:
System.out.println("2 Please head to the canteen to collect your order");
if (menu1 == 2) {
delivery = 0.00;
System.out.println("Please head to the canteen to collect your order");
}
break;
default:
System.out.println("Invalid selection");
break;
}
break;
case 2:
System.out.println("1.Bewley’s Breakfast Tea (Pot for €1.80)\n2.Peppermint €1.50\n3 Camomile €1.50");
menu = reader.nextInt();
if (menu == 1) {
selection = 1.80;
System.out.println("You have selected Bewley’s Breakfast Tea");
} else if (menu == 2) {
selection = 1.50;
System.out.println("You have selected Peppermint");
} else if (menu == 3) {
System.out.println("Camomile");
}
break;
case 3: //exit
System.exit(0);
default:
System.out.println("Invalid selection");
break;
}
}
This stops the whole problem with the switches calling when they should not but again if I try to get the strings I need it would print them again to quickly.
The only way I can see doing this is to ask for all the strings needed within the switch and doing all validation as well.
Is this the correct way of doing it or am I missing something here ?
Any help is appreciated thanks :)
You misunderstand how java syntax is working.
In your second example, you switch on menu:
switch (menu) {
case 1:
//if you have reached this, then menu is 1 and there is no further need to if on it, because it is 1, nothing else. It is exactly one.
}

Categories