Sidney Heier
Sidney Heier

Reputation: 97

Switch Menu Java

I have a switch menu and I want it to loop the entire menu including the directions but it just keeps looping the operation i select. How do I change it? I switched from a do/while to just a while loop.

 int count = 0;

    String first;
    String last;
    String num;
    Contact person;

    System.out.println("What would you like to do?");
    System.out.println("Type c to create");
    System.out.println("Tpe e to edit");
    System.out.println("Tpe d to delete");
    System.out.println("Type q to quit");

    Scanner input = new Scanner(System.in);
    char choice = input.next().charAt(0);

    AddressBook addressBook = new AddressBook();
    while ('q' != choice) {
        switch (choice) {

            case 'c':
                System.out.println("Enter first name, last name and phone number");

                addressBook.addContact();

                count++;

                System.out.println("Total number of contact: " + count);

                break;

            case 'e':
                System.out.println("Enter name to be edited");

                first = input.next();
                last = input.next();
                num = null;

                person = new Contact(first, last, num);
                addressBook.edit(person);

                break;
            case 'd':
                System.out.println("Enter name to be deleted");

                first = input.next();
                last = input.next();
                num = null;

                person = new Contact(first, last, num);

                addressBook.removeContact(person);
                break;
            default:
                System.out.println("Operation does not exist");
        }

    }
}

}

Upvotes: 1

Views: 1002

Answers (2)

Rahman
Rahman

Reputation: 3785

No need to use choice.

1.Change while ('q' != choice) to while (true)

2.Move below code inside while

     System.out.println("What would you like to do?");
     System.out.println("Type c to create");
     System.out.println("Tpe e to edit");
     System.out.println("Tpe d to delete");
     System.out.println("Type q to quit");

3. Add one extra case

 case 'q':

   break;

Upvotes: 1

CubeJockey
CubeJockey

Reputation: 2219

Initialize char choice to a default char:

char choice = 'a';

Then move all of this:

System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");

choice = input.next().charAt(0);

Inside your while loop:

while ('q' != choice) {
    //show menu options
    //allow user to select a menu option

    //use switch to operate based on user decision

    //once the operation is complete, as long as the user didn't select q, 
    //the menu options show once more and allow another selection
}

Upvotes: 2

Related Questions