How to Create a looping Menu in Java? - java

I am new to Java and learning. I am making a looping menu in Java. But when I select "a" and enter the details it doesn't go back to the menu.
I have done a bit of research and I need to add a Do and While loop here, but I'm confused on how to implement that here. A bit of guidance is extremely appreciated
Heres my code below:
switch(selection) {
case 'A':
case 'a':
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 'B':
case 'b':
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 'x':
case 'X':
System.out.println("Exiting data entry menu..");
break;
//equivalent to an else
default:
System.out.println("ERROR! - Please Enter a Valid Selection!");
}
while(selection != 'X');

Is this what you needed?
char selection;
do
{
do
{
//Menu
System.out.println("Toll Road Data Entry Menu");
System.out.println("-----------------------------------------");
System.out.println("A - Record Trip");
System.out.println("B - Record Breakdown Incident");
System.out.println("X - Exit");
System.out.print("Enter Your Selection: ");
selection = input.nextChar();
if (selection!='a' || selection!='A' || selection!='b' || selection!='B' || selection!='x' || selection!='X')
{
System.out.println("Selection must be a single character, A,B or X");
continue;
}
else
break;
} while (1);
switch(selection)
{
case 'A':
case 'a':
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 'B':
case 'b':
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 'x':
case 'X':
System.out.println("Exiting data entry menu..");
break;
//equivalent to an else
default:
System.out.println("ERROR! - Please Enter a Valid Selection!");
}
} while(selection != 'X');

I usually through them in while loops that way it just through me back to main menu when done
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
boolean menu=true;
int selection,sector_break;
String date,enter_point,exit_point,
breakdown;
double rec_cost;
while(true)
{
System.out.print(String.format("\033[2J"));
System.out.print("Your Menu Title \n\n");
System.out.print("1. Selection A\n");
System.out.print("2. Selection B\n");
System.out.print("3. Selection C\n");
System.out.print("4. Selection D\n");
System.out.print("5. Exit Menu D\n");
selection = Integer.parseInt(input.nextLine());
if(selection<1 || selection>4)
return;
switch(selection){
case 1:
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 2:
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 3:
// your code here
default:
// your code here
}
}
}
}

Related

Force the user to pick option 1 before option 2

I want to force the user to select choice 1 before they can proceed and select choice 2 any help would appreciated.
(note I've only done if,switch,while,for,do....while,methods and arrays in java so far)
Scanner sc = new Scanner(System.in);
int[] ages = new int[3];
int choice;
do {
System.out.println("Average Age program");
System.out.println("Enter 1 to enter ages");
System.out.println("Enter 2 to calculate the average Age");
System.out.println("Enter 0 to Exit");
choice = sc.nextInt();
switch(choice) {
case 1:
acceptAges(ages);
break;
case 2:
averageAge(ages);
break;
default:
System.out.print("invalid option");
}
} while(choice != 0);
}
You could simply not display choice 2 until 1 was chosen at least once.
Scanner sc = new Scanner(System.in);
int[] ages = new int[3];
int choice;
boolean is2Enabled=false,
do{
System.out.println("Average Age program");
System.out.println("Enter 1 to enter ages");
if(is2Enabled)
System.out.println("Enter 2 to calculate the average Age");
System.out.println("Enter 0 to Exit");
choice=sc.nextInt();
switch(choice)
{
case 1:
acceptAges(ages);
is2Enabled=true;
break;
case 2:
if(is2Enabled)
averageAge(ages);
else
System.out.print("invalid option");
break;
default:
System.out.print("invalid option");
}
}while(choice != 0);
}

My java code has no errors but why won't it run?

For some reason when I run my code on eclipse there is nothing showing on the screen like it should. I'm not sure what it is. I can type input into the console but that is about it. Nothing else happens. Can anyone tell me what it could be? Thanks.
import java.util.Scanner;
public class Test {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
Flight flight = new Flight (input.nextLine(), input.nextLine(), input.nextLine(), input.nextLine(), 0);
System.out.println("Creating first flight");
System.out.println("What is the name of the flight?");
String flightName = input.nextLine();
System.out.println("What is the destination of the flight?");
String destination = input.nextLine();
System.out.println("What is the departure time of the flight?");
String departureTime = input.nextLine();
System.out.println("What is the departure gate of the flight?");
String departureGate = input.nextLine();
boolean done = false;
while (!done) {
System.out.println("Now what would you like to do?");
System.out.print("1. Print out a flight's info");
System.out.print("2. Print out the number of flights through the static variable.");
System.out.print("3. Change the departure time of a flight.");
System.out.print("4. Change the departure gate of a flight.");
System.out.print("5. Exit");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Which flight would you like to print the info of (1 or 2)?");
int selection = 0;
selection = input.nextInt();
if (selection == 1 || selection == 2) {
Flight.printFlight();
} else{
System.out.println("Invalid Option");
} break;
case 2:
System.out.println("This is the number of flights" + Flight.getNumFlights());
break;
case 3:
System.out.println("Which flight would you like to change the departure time of (1 or 2)?");
int selection2 = 0;
selection2 = input.nextInt();
if (selection2 == 1 || selection2 == 2){
System.out.println("What is the new departure time for flight " + (Flight.getNumFlights()-1));
String newDeptTime = input.nextLine();
Flight.changeDeptTime(newDeptTime);
} else{
System.out.println("Invalid Option");
} break;
case 4:
System.out.println("Which flight would you like to change the departure gate of?");
int selection3 = input.nextInt();
if (selection3 == 1 || selection3 == 2){
System.out.println("What is the new departure gate for flight " + Flight.getNumFlights());
String newDeptGate = input.nextLine();
Flight.changeDeptGate(newDeptGate);
} else {
System.out.println("Invalid option");
} break;
case 5:
done = true;
break;
default:
System.out.println("Invalid option");
break;
}
}
}
}
its not showing anything because it is waiting for you to enter characters you want in the Flight class constructor.
As you can see here
Flight flight = new Flight (input.nextLine(), input.nextLine(), input.nextLine(), input.nextLine(), 0);
execution stops at the input.nextLine() parts till you enter something and hit enter
P.S : its better to place some System.out.println("enter the value") kind of statement before the input parts to show the user what to do.funny doing this will prevent you from making this mistake you made

counter for errors

when user logs out the user may choose to log back in again. For Logging back in: If the user get the pin code wrong 3 times, the program terminates.
System.out.println("You have logged out");
System.out.print("Please Enter Pin: ");
pin2 = sc.nextInt();
while (pin != pin2){
while (ctr < 2){
System.out.print("Please Enter Pin: ");
pin2 = sc.nextInt();
ctr++;
}
}
If I understand your problem correctly you will want to have something like that:
while (pin == pin2) {
System.out.println("What would you like to do?");
System.out.println("1 - Check Balance");
System.out.println("2 - Deposite");
System.out.println("3 - Withdraw");
System.out.println("4 - Change Pin");
System.out.println("5 - End Transaction");
sel = sc.nextInt();
switch (sel) {
case 1:
System.out.println("Your current balance is " + bal);
break;
case 2:
System.out.println("How much would you want to deposite? ");
dep = sc.nextInt();
bal = dep + bal;
System.out.println("Your new current balance is " + bal);
break;
case 3:
System.out.println("How much would you want to Withdraw? ");
with = sc.nextInt();
if (with > bal) {
System.out.println("You do not have that amount on your account! Please enter again.");
} else {
System.out.println("You withdrew " + with);
bal = bal - with;
System.out.println("Your new current balance is " + (bal));
}
break;
case 4:
System.out.print("Please enter a new pin: ");
pin = sc.nextInt();
System.out.println("Please verify your new pin: ");
pin2 = sc.nextInt();
break;
case 5:
System.out.println("Please Enter Pin: ");
pin = sc.nextInt();
break;
default:
break;
}
}
Basically, I've deleted the loop label, it is not necessary and I consider it a bad style. I've also changed the while condition, so the program runs as long as user enters exactly the same pin as he confirmed at the beginning. Moreover, I think it is better to read the value of sel after printing instructions, not before as you did.
Like what been said in the comments, avoid using Labels and/or goto rep.
Use something like that :
import java.util.Scanner;
public class AtmMachine {
public static void main(String[] args){
int actualPin = -1;
int sel = 0, pin, pin2, check, ctr = 0, dep, with, bal = 10000;
Scanner sc = new Scanner(System.in);
while(actualPin == -1)
{
System.out.print("Please enter a new pin: ");
pin = sc.nextInt();
System.out.print("Please verify your new pin: ");
pin2 = sc.nextInt();
if(pin == pin2) actualPin = pin;
else System.out.println("Error");
}
boolean logged = false;
while (true){
if(logged){
System.out.println("What would you like to do?");
System.out.println("1 - Check Balance");
System.out.println("2 - Deposite");
System.out.println("3 - Withdraw");
System.out.println("4 - Change Pin");
System.out.println("5 - End Transaction");
sel = sc.nextInt();
switch (sel){
case 1:
System.out.println("Your current balance is "+ bal);
break;
case 2:
System.out.println("How much would you want to deposite? ");
dep = sc.nextInt();
bal= dep+bal;
System.out.println("Your new current balance is "+ bal);
break;
case 3:
System.out.println("How much would you want to Withdraw? ");
with = sc.nextInt();
if(with > bal){
System.out.println("You do not have that amount on your account! Please enter again.");
}
else{
System.out.println("You withdrew "+ with);
bal = bal-with;
System.out.println("Your new current balance is "+ (bal));
}
break;
case 4:
System.out.print("Please enter a new pin: ");
pin = sc.nextInt();
System.out.println("Please verify your new pin: ");
pin2 = sc.nextInt();
if(pin == pin2) actualPin = pin;
else System.out.println("Error");
break;
case 5:
logged = false;
break;
default:
break;
}
else{
System.out.println("Please Enter Pin: ");
sel = sc.nextInt();
logged = actualPin == sel;
}
}
}
}

Java while loop doesn't work as intended

public static void main(String[] args) {
boolean run = true;
while (run) {
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to MetricMan - the best converter in town!");
System.out.println("Choose and option:");
System.out.println("A) Fahrenheit to Celsius");
System.out.println("B) Celcius to Fahrenheit");
System.out.println("C) Miles to Kilometers");
System.out.println("D) Kilometers to Miles");
System.out.println("E) Inches to Centimeters");
System.out.println("F) Centimeters to Inches");
System.out.println("X) Quit the program");
System.out.print("Your choice > ");
String choice = kb.nextLine();
double output; int input;
System.out.print("Enter the number of ");
switch (choice) { // do actions according to the user's choice. convert and display
case "A":
System.out.print("Farenheit > ");
input = kb.nextInt();
output = convertFtoC(input);
System.out.println(input+" farenheit is "+output+" celsius");
break;
case "B":
System.out.print("Celsius > ");
input = kb.nextInt();
output = convertCtoF(input);
System.out.println(input+" celsius is "+output+" farenheit");
break;
case "C":
System.out.print("miles > ");
input = kb.nextInt();
output = convertMtoK(input);
System.out.println(input+" miles is "+output+" kilometres");
break;
case "D":
System.out.print("kilometres > ");
input = kb.nextInt();
output = convertKtoM(input);
System.out.println(input+" kilometres is "+output+" miles");
break;
case "E":
System.out.print("inches > ");
input = kb.nextInt();
output = convertItoC(input);
System.out.println(input+" inches is "+output+" centimeters");
break;
case "F":
System.out.print("centimeters > ");
input = kb.nextInt();
output = convertCtoI(input);
System.out.println(input+" centimeters is "+output+" inches");
break;
case "X":
System.out.println(); System.out.println();
System.out.println("May the odds be ever metric!");
run = false;
break;
}
System.out.println();
kb.nextLine();
}
} // end of main()
there's my main method. As seen in the code, when X has been entered the code should stop running straight away, however its actual output is
...
Your choice > X
Enter the number of
May the odds be ever metric!
there is a "enter the number of " before the actualy intended output and I see no reason for it to be there. Can anyone help fix this?
You are doing System.out.print("Enter the number of "); in every case .So thats why its printing when you entered X so try to put System.out.print("Enter the number of "); inside if(check if string entered is not X) like below
if(!choice.equals("X")){
System.out.print("Enter the number of ");
}
OR
put System.out.print("Enter the number of "); inside each switch case where you want it as pointed by #Tanmoy
That line occurs every time you go through the loop. One way to fix this is to make that call in each case statement except for X.
In your code
System.out.print("Enter the number of ");
switch (choice) { // do actions according to the user's choice. convert and display
so you are basically printing this before switch, so the output is expected, you may want to call inside cases rather outside switch, when its x, just quit.

Java scanner not returning multiple word variable

This section of my code is not working as I need it to. I need to Select from the menu either A, B, or X and then input a small sentence for the description (multiple) a figure for the cost. I can input all the data perfectly and it returns to the menu (only exiting once inputing X). But the return string for the variable damageDesc is only grabbing the first word prior to the space. I've tried this all night and still can't get it to return all words in the string. Here's the code if anyone can help. Thanks!
do {
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
menuOption = console.next().charAt(0);
switch (menuOption) {
case 'A':
case 'a':
System.out.print("Enter description of damage repair: ");
damageDesc = console.next();
console.nextLine();
System.out.print("Enter repair cost: ");
damageCost= console.nextDouble();
//Place damage description and cost on seperate lines
damageDescFinal = String.format(damageDescFinal + "- %s ($%.2f ) \n", damageDesc, damageCost);
//Also could have used the below
//damageDescFinal = (damageDescFinal+"- "+damageDesc+
// " ($"+damageCost+")"+"\n");
//All damage costs added together
damageCostFinal = damageCostFinal + damageCost;
System.out.println();
break;
case 'B':
case 'b':
System.out.print("Enter details of traffic infringement: ");
fineDesc = console.next();
console.nextLine();
System.out.print("Enter traffic fine amount: ");
fineCost = console.nextDouble();
//Set fine description and cost on seperate lines
fineDescFinal = String.format(fineDescFinal + "- %s ($%.2f ) \n", fineDesc, fineCost);
//Also could have used the below
//fineDescFinal = fineDescFinal+"- "+fineDesc+
// " ($"+fineCost+")"+"\n";
//All fine costs added together
fineCostFinal = fineCostFinal + fineCost;
System.out.println();
break;
case 'X':
case 'x':
//Exit the damage and fine menu
System.out.print("Exiting data entry menu..."+"\n");
System.out.println();
break;
default:
//Error handling for invalid input
System.out.print("***ERROR*** Invalid Selection!"+"\n");
System.out.println();
break;
}
} while (menuOption != 'X' && menuOption != 'x');
Perhaps, you need to use nextLine() for reading the entire line instead of next
Fixed this myself by changing the Double values to strings and then converted them back to a double after the inputs were finished. This solved the scanner problems I was having. Here's the final code that worked:
do {
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
menuOption = console.next().charAt(0);
//Switch to allow either upper or lower case menuOption
switch (menuOption) {
case 'A':
case 'a':
System.out.print("Enter description of damage repair: ");
//Clear scanner
console.nextLine();
//Input damage description
damageDesc = console.nextLine();
System.out.print("Enter repair cost: ");
//Input damage cost
damageCost= console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleDamageCost = Double.parseDouble(damageCost);
//Set damage description and cost on seperate lines for each input
damageDescFinal = String.format(damageDescFinal + "- %s ($%.2f ) \n", damageDesc, doubleDamageCost);
//Concatenate all fine costs for a final value
damageCostFinal = damageCostFinal + doubleDamageCost;
System.out.println();
break;
case 'B':
case 'b':
System.out.print("Enter details of traffic infringement: ");
//Clear scanner
console.nextLine();
//Input fine description
fineDesc = console.nextLine();
System.out.print("Enter traffic fine amount: ");
//Input fine cost
fineCost = console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleFineCost = Double.parseDouble(fineCost);
//Set fine description and cost on seperate lines for each input
fineDescFinal = String.format(fineDescFinal + "- %s ($%.2f ) \n", fineDesc, doubleFineCost);
//Concatenate all fine costs for a final value
fineCostFinal = fineCostFinal + doubleFineCost;
System.out.println();
break;
case 'X':
case 'x':
//Exit the damage and fine menu
System.out.print("Exiting data entry menu..."+"\n");
System.out.println();
break;
default:
//Error handling for invalid input
System.out.print("***ERROR*** Invalid Selection!"+"\n");
System.out.println();
break;
}
//Exits menu loop and allow code to continue
} while (menuOption != 'X' && menuOption != 'x');
why not in this case use .ToLowerCase or .ToUperCase? this way you can get a cleaner code
do {
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
Scanner console = new Scanner(System.in);
menuOption = console.next().toLowerCase().charAt(0);
//Switch to allow either upper or lower case menuOption
switch (menuOption) {
case 'a':
System.out.print("Enter description of damage repair: ");
//Clear scanner
console.nextLine();
//Input damage description
damageDesc = console.nextLine();
System.out.print("Enter repair cost: ");
//Input damage cost
damageCost= console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleDamageCost = Double.parseDouble(damageCost);
//Set damage description and cost on seperate lines for each input
damageDescFinal = String.format(damageDescFinal + "- %s ($%.2f ) \n", damageDesc, doubleDamageCost);
//Concatenate all fine costs for a final value
damageCostFinal = damageCostFinal + doubleDamageCost;
System.out.println();
break;
case 'b':
System.out.print("Enter details of traffic infringement: ");
//Clear scanner
console.nextLine();
//Input fine description
fineDesc = console.nextLine();
System.out.print("Enter traffic fine amount: ");
//Input fine cost
fineCost = console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleFineCost = Double.parseDouble(fineCost);
//Set fine description and cost on seperate lines for each input
fineDescFinal = String.format(fineDescFinal + "- %s ($%.2f ) \n", fineDesc, doubleFineCost);
//Concatenate all fine costs for a final value
fineCostFinal = fineCostFinal + doubleFineCost;
System.out.println();
break;
case 'x':
//Exit the damage and fine menu
System.out.print("Exiting data entry menu..."+"\n");
System.out.println();
break;
default:
//Error handling for invalid input
System.out.print("***ERROR*** Invalid Selection!"+"\n");
System.out.println();
break;
}
//Exits menu loop and allow code to continue
} while (menuOption != 'x');
but you should do more classes like
Public void menu(){
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
}
and so on, to get a more organized and clean code. segementation is your best friend.

Categories