【问题标题】:What am I doing wrong do get this extra output? [duplicate]我做错了什么得到这个额外的输出? [复制]
【发布时间】:2014-11-13 22:02:10
【问题描述】:
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

我脑子里一直在想,想不通

【问题讨论】:

  • 你想做什么?并请提供可以成功编译的代码,无需猜测其余部分。
  • keyboard.nextInt() 之后使用keyboard.nextLine();(并丢弃结果)以使用换行符。否则下一个targetUPC = keyboard.nextLine() 将使用换行符,从而导致一个空字符串。
  • 谢谢 ajb,这完全有道理,我应该记住这一点

标签: java


【解决方案1】:

您正在混合nextInt(),它留下尾随换行符,nextLine() 在一个循环中。阅读尾随的换行符,例如,

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

或者首先消耗整行,例如,

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-28
        • 2021-09-17
        • 1970-01-01
        • 2022-12-06
        • 2019-12-21
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        相关资源
        最近更新 更多