我做错了什么来获得额外的输出?

时间:2014-11-13 22:02:11

标签: java

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");
    }

以下是它的一些输出:

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

我一直在脑子里经历它无法弄清楚

3 个答案:

答案 0 :(得分:2)

你正在混合nextInt(),它留下尾随换行符,并在循环中留下nextLine()。阅读尾随换行符,

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

或者首先消耗整行,

numOfItems = Integer.parseInt(keyboard.nextLine().trim());

答案 1 :(得分:1)

当用户输入numOfItems的输入行时,nextInt()不会消耗该行。因此,当您回到循环的开头并调用targetUPC = keyboard.nextLine();时,您将获得已输入的行的剩余部分。在阅读nextLine();之后,请调用numOfItems以消耗为下一个循环准备好的其余输入。

答案 2 :(得分:0)

nextInt()将在输入缓冲区中留下未读的换行符。

这个新行随后由nextLine()调用处理,然后返回一个空字符串,该字符串被分配给targetUPC,并且可能没有匹配的RetailItem ......

相关问题