0

why did this worked:

    do{
    System.out.println("\nWhich food or beverage would you like to order? ");
    int OrderNum;
    OrderNum = scan.nextInt();
    
    switch(OrderNum){
        case 1:
             System.out.println("\nHow many quanitites would you like to order?");
             NasiAyamPenyet.quantity = scan.nextInt();
             break;
             
        case 2:
             System.out.println("\nHow many quanitites would you like to order?");
             NasiKukus.quantity = scan.nextInt();
             break;
             
        case 3:
             System.out.println("\nHow many quanitites would you like to order?");
             NasiAyamHainan.quantity = scan.nextInt();
             break;
    }
    System.out.println("\nWould you like to order more?");
    i = scan.nextInt();
    }
    while(i<2);

But the loop will ignore the string input in this one, there is only little difference in the code, I changed it so the user inputs a yes and no line that will then be converted back to the original code. I don't understand why it wouldn't work :

   do{
    System.out.println("\nWhich food or beverage would you like to order? ");
    int OrderNum;
    OrderNum = scan.nextInt();
    
    switch(OrderNum){
        case 1:
             System.out.println("\nHow many quanitites would you like to order?");
             NasiAyamPenyet.quantity = scan.nextInt();
             break;
             
        case 2:
             System.out.println("\nHow many quanitites would you like to order?");
             NasiKukus.quantity = scan.nextInt();
             break;
             
        case 3:
             System.out.println("\nHow many quanitites would you like to order?");
             NasiAyamHainan.quantity = scan.nextInt();
             break;
    }
    System.out.println("\nWould you like to order more?");
    ans = scan.nextLine();
    if(ans.equals("yes")){
        i = 1;
    }
    else if(ans.equals("no")){
        i=2;
    }
    }
    while(i<2);
  • ```i``` can't be 2 because ```while(i<2)``` work upto ```i=1``` – TinsG May 27 '21 at 15:27
  • 1
    @TinsG I think the point is to exit the loop if `"no"` is entered. – Dave Newton May 27 '21 at 15:31
  • 1
    I think `scan.nextLine()` is taking the remainder of the line on which you entered `orderNum`, instead of the following line on which you would answer "yes". Have you tried using `Integer.parseInt(scan.nextLine())` instead of `scan.nextInt()` for assigning `orderNum`, to avoid this problem? – Green Cloak Guy May 27 '21 at 15:33
  • @Dave Newton if that's the case then it should use ```break``` to exit the loop – TinsG May 27 '21 at 15:33
  • @TinsG :shrug: Sure, could do that too. How to get out of the loop is orthogonal to the problem, though. – Dave Newton May 27 '21 at 15:35

0 Answers0