-1

I am using a do-while loop that loops based on the input of the user as a 'Y' or 'N'. If the user chooses to continue by pressing 'Y' or 1 (for simplicity), on the second iteration it skips the first input in the same loop.

do{
       System.out.println("Enter the location: ");
       cartItem.purchaseLocation = input.nextLine();  // This input is skipped on second iteration

       System.out.println("Enter the product description: ");
       cartItem.productDescription = input.nextLine();

       System.out.println("Enter the price of the item: ");
       cartItem.productPrice = input.nextDouble();

       System.out.println("Enter the quantity: ");
       cartItem.quantity = input.nextInt();


       cartList.add(cartItem);

       System.out.println("Do you want to add more items ? y = 1 / n = 0: ");
       exitVar = input.nextInt();

   }while(exitVar!=0);            // Repeat till no more items need to be added in the cart

So when the user presses input 0 to repeat the procedure, the line

cartItem.purchaseLocation = input.nextLine();

which is the very first input in the loop will be skipped. Any suggestions what might be wrong here ?

noobcoder
  • 11,983
  • 10
  • 39
  • 62

2 Answers2

1

same question as Skipping nextLine() after use nextInt()

input.nextInt() does not read a line, when your input is "1\n", it read "1" and leaves "\n" to the next read, which is

cartItem.purchaseLocation = input.nextLine();
Community
  • 1
  • 1
MagicFingr
  • 479
  • 6
  • 20
-1

Instead of using input.nextLine() use input.next() assuming input is a Scanner object.

If it is not, please clarify what input is.

user3062600
  • 59
  • 1
  • 5