Create a loop in a java program - java

I'm trying to write a program in which the user will first be shown a menu from which they can select a number of options. I have tried to create a code which, once an option has been selected will return the user to the menu. However, the program simply ends rather than looping the user back to the menu. What do I need to add to the code so that once the selection methods have been run through it will return the user to the selection menu?
Here's an excerpt showing the relevant part of the program:
Scanner scanner = new Scanner(System.in);
int selection = 0;
while (x == 0) {
System.out.println("Please make a selection");
System.out.println("[1] Make a new booking");
System.out.println("[2] View films");
System.out.println("[3] View Screens");
System.out.println("[4] View Customers");
System.out.println("[5] View showing information");
System.out.println("[6] View booking information");
System.out.println("[7] Exit");
while (selection == 0) {
System.out.println("Selection: ");
try {
selection = scanner.nextInt();
} catch (InputMismatchException nfe) {
System.out.println("Input must be a number");
selection = 0;
scanner = null;
scanner = new Scanner(System.in);
}
}
switch (selection) {
case 1:
System.out.println("All available showings:");
x = 1;
for (Showing aShowing : showingList) {
System.out.println(aShowing.toString());
}
System.out.println("Enter the showing number: ");
int show = scanner.nextInt();
Showing userChoice = showingList.get(show - 1);
System.out.println("Enter the number of tickets: ");
int tickets = scanner.nextInt();
Booking booking1 = new Booking(customerA, userChoice, tickets);
System.out.println(booking1);
break;
case 2:
System.out.println("Current films being shown:");
x = 1;
System.out.println("Film one: " + filmA.getTitle()
+ ".\nLength: " + filmA.getDuration() + " minutes."
+ "\nAge Rating: " + filmA.getAgeRating()
+ ".\nDescription: " + filmA.getDescription() + ".");
break;
case 3:
System.out.println("Screen information:");
x = 1;
System.out.println("Screen id:" + screenA.getId()
+ ".\nSeats a maximum of " + screenA.getCapacity() + " people.");
break;

I don't understand what while(x==0) is doing there.
What I have understood from your requirement is, you want to offer user a menu with options and user needs to enter his choice and a operation will be performed according to that and then again ask for another input from user.
If this is the case, then try writing your logic the following way,
do{
System.out.println("Please make a selection");
System.out.println("[1] Make a new booking");
System.out.println("[2] View films");
System.out.println("[3] View Screens");
System.out.println("[4] View Customers");
System.out.println("[5] View showing information");
System.out.println("[6] View booking information");
System.out.println("[7] Exit");
selection = scanner.nextInt();
switch(selection){
case 1:
...
//so on
case 7:
//do nothing
break;
default:
System.out.println("Wrong number entered");
}
}while(selection!=7);

Related

Add method and while loop do not execute properly

This program is a contact book. There is a contact class and contact book class. When I execute case 2, the add method from the contact book class does not let me enter name and phone number individually. "Enter a name" and "Enter an address" appear at the same time.
Here is the switch case in the main method:
while (!done)
{
ContactBook cb = new ContactBook();
System.out.println("1) List all contacts" + "\n" + "2) Add a contact"
+ "\n" + "3) Update a contact" + "\n" + "4) Remove a contact" +
"\n" + "5) Quit");
userChoice = sc.nextInt();
switch (userChoice)
{
case 1:
c.toString();
break;
case 2:
cb.add(sc);
break;
case 3:
cb.update(sc);
break;
case 4:
cb.remove(sc);
}
if (userChoice == 5);
{
done = true;
}
}
}
Here is the add method from the contact book class:
public void add (Scanner sc)
{
Contact c = new Contact(name, address, phone, email);
System.out.println("Enter a name: ");
c.setName(sc.nextLine());
System.out.println("Enter an address: ");
c.setAddress(sc.nextLine());
System.out.println("Enter a phone number: ");
c.setPhone(sc.nextLine());
System.out.println("Enter an email: ");
c.setEmail(sc.nextLine());
entries = Arrays.copyOf(entries, entries.length + 1);
}
You need to change the following:
userChoice = sc.nextInt();
to
userChoice = Integer.valueOf(sc.nextLine());
I think this should fix your problem
System.out.print("Enter a name: ");
c.setName(sc.nextLine());
System.out.println()

Passing user input between cases in switch java

I have a small problem with this code. I added lecturer in case 1 and I trying to add books to this lecturer in case 3. problem is that it seems that case 3 doesn't recognize the created lecturer.
Is there any way to pass this value.
The solution is probably very simple but at this hour I just can not get it...
public class Menu {
static Scanner in = new Scanner (System.in);
LectureList lec = new LectureList(100);
BookList bl = new BookList(0);
public Menu(){
}
public int mainMenu(){
int option = 0;
System.out.println("---------------------------------------------------------");
System.out.println(" Lecturer Menue ");
System.out.println("*********************************************************");
System.out.println("1) Add Lecturer");
System.out.println("2) Find Lecturer by ID");
System.out.println("3) Add book to Lecturer BookList");
System.out.println("4) Remove book from Lecturer BookList ");
System.out.println("5) Search for a book using the ISBN number");
System.out.println("6) Calculate the yearly book payment");
System.out.println("7) Output all of the book details in the system to a file");
System.out.println("8) Exit");
boolean selected = false;
while (selected == false)
{
try
{
option = in.nextInt();
in.nextLine();
if
((option == 8)){
System.out.println("Goodbye!");
System.exit(0);}
else if
((option <= 0) || (option > 8))
System.out.println("Sorry but you have to choose an option between 1 and 8");
else
selected = true;
}
catch (InputMismatchException e)
{
System.out.println("Sorry you did not enter a valid option");
in.next();
}
}
return option;
}
public void menuSwitch(){
boolean finish = false;
if (finish == false){
int option = mainMenu();
switch (option){
case 1:
String LecName = " ";
System.out.println("Please enter Lecturer's name");
LecName = in.nextLine();
Lecturer l = new Lecturer(LecName);
lec.add(l);
break;
case 2:
break;
case 3:
String name = "";
Double price = 00.00 ;
String isbn ="";
String author = "";
System.out.println("Please enter Book title ");
name = in.nextLine();
System.out.println("Please enter Book's price ");
price = in.nextDouble();
System.out.println("Please enter Book's isbn number ");
isbn = in.next();
System.out.println("Please enter book author's name");
author = in.next();
Book b = new Book( name, price, isbn, author);
l.addBook(b);
break;``
default:
finish = true;
break;
}
menuSwitch();
}
}
}
Every case statement in your switch finishes with a break;, and the default case does as well. In that case, for any pass through the switch statement, only a single case label will be executed.
If the first pass executes the first case, and the second pass executes the second case, the variables defined in the first case will no longer be around -- they will have fallen out of scope when the switch statements completes the first time.
Can you get a reference to your Lecturer from the LectureList collection?
In case 1: you can create it and put it in the collection; in case 3: you can obtain it back from the collection and update it.

How do I get the menu program to restart after completing a selection?

My program is stuck in an infinite loop after a selection is made and completed. It needs to restart and go through the menu options again. Any help would be greatly appreciated.
public static void main(String[] args) {
// TODO Auto-generated method stub
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
int choice = input.nextInt();
int count = 0;
while (choice < 1 || choice > 6){
count ++;
System.out.println("I'm sorry, " +choice+ " is not a valid option.\n");
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
choice = input.nextInt();
if (choice >= 1 && choice <= 6){
continue;
}
else if (count == 2){
System.out.println("Please try again later.");
System.exit(0);
return;
}
}
do
{
switch (choice)
{
case 1: choice = 1;
System.out.print("What is the first number? ");
int firstAdd = input.nextInt();
System.out.print("What is the second number? ");
int secondAdd = input.nextInt();
System.out.println("Answer: " +(firstAdd + secondAdd));
break;
case 2: choice = 2;
System.out.print("What is the first number? ");
int firstSub = input.nextInt();
System.out.print("What is the second nubmer? ");
int secondSub = input.nextInt();
System.out.println("Answer: " +(firstSub - secondSub));
break;
case 3: choice = 3;
System.out.print("What is the first number?" );
int firstMult = input.nextInt();
System.out.print("What is the second number? ");
int secondMult = input.nextInt();
System.out.println("Answer: " +(firstMult * secondMult));
break;
case 4: choice = 4;
System.out.print("What is the first number? ");
double firstDiv = input.nextInt();
System.out.print("What is the second number? ");
double secondDiv = input.nextInt();
while (secondDiv == 0){
System.out.println("I'm sorry, you can't divide by zero.");
break;}
{
System.out.println("Answer: " +(firstDiv / secondDiv));
break;
}
case 5: choice = 5;
System.out.println(Math.random() * 10 + 1);
break;
case 6: choice = 6;
System.out.println("Goodbye!");
System.exit(0);
return;
}
}while (choice >=1 && choice <= 6);
}
I've tried a few different options that I found in my book, but they seem to cause more errors in other areas. I don't know if there is a different statement than "break;" to use to restart the menu because this is my first time using cases.
Enclose everything after the scanner instantiation in a while loop.
Specifically,
while (true) {
// your code
if (choice == 6)
break;
}
FIXED: Also remove the do {} while() loop. Your loop is infinite because "choice" does not change in the loop.

Restrict Switch Statement order

I am writing a menu in java using a switch statement and while loop. I am looking to find a way of ensuring the user completes menu one before proceeding to menu two.
Here is an example piece of code:
(Please note I normally pass data using setters and getters, this is just a quick program I wrote for this question)
package menuOrder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int option = 0;
String Fname = null;
String Sname = null;
int Age = 0;
while(option !=5){
System.out.println("1. Enter Firstname");
System.out.println("2. Enter Surname");
System.out.println("3. Enter Age");
System.out.println("4. Display Details");
System.out.println("5. System Exit");
option = sc.nextInt();
switch(option){
case 1:
System.out.println("Please enter your Firstname >");
Fname = sc.next();
break;
case 2:
System.out.println("Please enter your Surname >");
Sname = sc.next();
break;
case 3:
System.out.println("Please enter your Age >");
Age = sc.nextInt();
break;
case 4:
System.out.println("Firstname = " + Fname + "\nSurname = " + Sname + "\nAge = " + Age);
break;
case 5:
System.out.println("You have chosen to System Exit!!!");
System.exit(0);
break;
default:
System.out.println("Invalid Entry!! \nPlease try again");
}
}
}
}
I am trying to prevent the use from entering their Surname before their Firstname.
Can someone please help?
Thanks
First show only the first name. Then when the user enters first name call surname method from that method.Use method calls instead of switch case.

Java switch results (needing to print the values)

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

Categories

Resources