-3
public void addPizza() throws FileNotFoundException {
    Menu menu = new Menu();
    Map<Integer, Pizza> pizzaMenu = menu.getPizzaMenu();

    boolean exit = false;

    while (!exit) {
        String input1;
        String input2;

        System.out.println("What pizza");
        input1 = sc.nextLine();

        System.out.println("How many pizzas");
        input2 = sc.nextLine();

        if (input1.equals("Quit") || input1.equals("quit") || input2.equals("Quit") || input2.equals("quit")) {
                exit = true;
        } else {
            Pizza pizza = pizzaMenu.get(Integer.parseInt(input1));
            Integer quantity = Integer.parseInt(input2);

            OrderLineItem orderLine = new OrderLineItem(pizza,quantity,"");

            listOfOrderLineItems.add(orderLine);

Hello. I've got the above code, however my loop will not exit correctly. As it stands now, It'll ask you "What pizza" -> input Quit -> "How many pizzas" -> input Quit. The idea is that it just quits the loop after typing Quit once, either in the What pizza or How many pizzas.

IMO it should exit after just one "Quit", since the if statement should set the boolean to true? Hope anyone can help.

Kind regards

Malthe22
  • 3
  • 3
  • 3
    Perhaps there is another loop elsewhere, so `addPizza()` gets called repeatedly. – Andreas Apr 16 '21 at 06:48
  • 2
    See also: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045/5221149) – Andreas Apr 16 '21 at 06:49
  • 2
    *Recommend:* Instead of `input1.equals("Quit") || input1.equals("quit")`, use `input1.equalsIgnoreCase("quit")`. – Andreas Apr 16 '21 at 06:50
  • 1
    You should **debug** your code to find out what's going wrong. See: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Apr 16 '21 at 06:52
  • you are taking input two times before if condition so it would expect two times input before it actually comes out. Whats wrong ? – Pramod Apr 16 '21 at 07:19

2 Answers2

1

Of course it behaves like this. Your if to check for the input "quit" comes after the second question.

The easiest change for this program to behave like you want is to put the same quit-check again after the first question and then instead of using the exit-flag make a break statement. The while could then be a "while(true)".

So in short it would look like this:

while (true) {
    String input1 = readline("What pizza");
    if (isQuit(input1)) {
        break;
    }
    String input2 = readLine("How many pizzas");
    if (isQuit(input2)) {
        break;
    }
    // do your stuff
}
0

Instead of changing the value of variable

exit

you can just use the

break

command and keep the while-loop running until it breaks.