gpt4 book ai didi

java - 我做错了什么会得到这个额外的输出吗?

转载 作者:行者123 更新时间:2023-12-01 22:35:36 25 4
gpt4 key购买 nike

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

我脑子里想了很久,还是想不出来

最佳答案

您正在将 nextInt()nextLine() 混合在一个循环中,该 nextInt() 会留下尾随换行符。读取尾随换行符,例如,

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

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

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

关于java - 我做错了什么会得到这个额外的输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com