0
System.out.println("Enter UPC for an item you want, enter -1 when done");

do {
    System.out.print("\nEnter a UPC ");
    targetUPC = keyboard.nextLine();
    RetailItem temporary = new RetailItem("Default", 0, 0, targetUPC);

    if(itemList.indexOf(temporary) > -1) {
        RetailItem itemIndex = itemList.get(itemList.indexOf(temporary));
        System.out.println("\n" + itemIndex);
        System.out.print("How many would you like? ");
        numOfItems = keyboard.nextInt();
        itemIndex.setInStock(itemIndex.getInStock() - numOfItems);
        totalCost = numOfItems * itemIndex.getPrice();
    }

    if(itemList.indexOf(temporary) == -1 && !targetUPC.equals("0")) {
        System.out.print(targetUPC + " not found.\n");
    }

Here's some output for it:

Enter UPC for an item you want, enter -1 when done

Enter a UPC: 999

999 not found.

Enter a UPC: 61835

Description: Corn Crisps
Price: $9.45
Number in stock: 35
UPC: 61835

How many would you like? 5

Enter a UPC  not found.                  //Why am I getting this?

Enter a UPC 0

Total cost: $47.25

I've been going through it in my head and can't figure it out

robertoia
  • 2,092
  • 20
  • 27
Color09
  • 1
  • 4
  • 1
    What are you trying to do? and please supply code which can be successfully compiled without having to guess the rest. – vallentin Nov 13 '14 at 22:04
  • 1
    Use `keyboard.nextLine();` (and throw away the result) after `keyboard.nextInt()` in order to consume the newline. Otherwise the next `targetUPC = keyboard.nextLine()` will consume the newline resulting in an empty string. – ajb Nov 13 '14 at 22:04
  • Thank you ajb that makes complete sense, I should have remembered that – Color09 Nov 13 '14 at 22:07

3 Answers3

2

You are mixing nextInt() which leaves trailing newline, with nextLine() in a loop. Read the trailing newline like,

numOfItems = keyboard.nextInt();
keyboard.nextLine();

Or consume the entire line in the first place like,

numOfItems = Integer.parseInt(keyboard.nextLine().trim());
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
1

When the user enters a line of input for numOfItems, nextInt() does not consume that line. So when you get back to the start of the loop and call targetUPC = keyboard.nextLine();, you get the remains of the line already entered. Put in a call to nextLine(); after you read numOfItems to consume the rest of the input ready for the next loop.

khelwood
  • 46,621
  • 12
  • 59
  • 83
0

nextInt() will leave an unread newline in the input buffer.

This newline is subsequently processed by the nextLine() call, which then returns an empty string, which gets assigned to targetUPC and there is presumably no matching RetailItem…

EricM
  • 442
  • 2
  • 4