【发布时间】: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