我正在尝试编写一个程序,模仿CS类的自动售货机的操作。我有一个双数组库存,它表示特定“插槽”中的物品数量[我的自动售货机很奇怪,有点像一台自动售货机,有一列不同的物品]。这是我到目前为止的代码:为什么我的代码给出错误输出?
public class VendingMachine
{
// define fields here
public static double itemPrice[];
public static String[] itemName;
public static int stock[][];
public static int maxPerSlot;
public static double cashAmmount;
public VendingMachine(int numslots, int maxperslot, double cash)
{
final int numSlots = numslots;
maxPerSlot = maxperslot;
cashAmmount = cash;
stock = new int[numSlots][1];
itemPrice = new double[numSlots];
itemName = new String[numSlots];
// complete this method
}
public void setProduct(int slot, String product, double price)
{ int Slot = slot;
itemPrice[Slot] = price;
itemName[Slot] = product;
stock[Slot][0] = 0;
//
}
public void restockProduct(String product, int quantity)
{
String Product = product;
int Quantity = quantity;
for(int i = 0; i < itemName.length;i++){
if (Quantity > (maxPerSlot-stock[i][0])){
return;
}
if (Product.equals(itemName[i])&&Quantity < maxPerSlot){
stock[i][0] += Quantity;
}else if ((maxPerSlot-stock[i][0])==0){
continue;
}
}
//Put # of products in slot that holds it and if that slot is full put the rest in the next
//available slot that holds that product, if all full return error.
}
public double getCashOnHand()
{
return cashAmmount; // replace this line with your code
}
public int getQuantity(int slot)
{
return stock[slot][0]; // replace this line with your code
}
public int getQuantity(String product)
{ int total = 0;
for (int i = 0; i<itemName.length;i++){
if (product == itemName[i]){
total += this.getQuantity(i);
}
}
return total;
}
public boolean buyItem(int slot)
{ int snum = slot;
double price = 0;
if (stock[snum][0] != 0){
stock[snum][0]--;
price= itemPrice[snum];
cashAmmount += price;
return true;
} else {
return false;}
// replace this line with your code
}
}
和运行的主要方法是:
public class vmd
{
public static void main(String[] args)
{
boolean success;
// vending machine w/ 20 slots, 10 items maximum per slot, $5 cash on hand
VendingMachine v = new VendingMachine(20, 10, 5.00);
v.setProduct(0, "Cheesy Poofs", 0.75);
v.setProduct(1, "Red Bull", 1.25);
v.setProduct(2, "Cheesy Poofs", 0.75);
v.restockProduct("Cheesy Poofs", 8);
v.restockProduct("Red Bull", 7);
v.restockProduct("Cheesy Poofs", 5); // 2 more go into slot 0, remaining 3 into slot 2
success = v.buyItem(0);
System.out.println(success); // should print "true"
System.out.println(v.getCashOnHand()); // should print "5.75"
System.out.println(v.getQuantity(2));// should print "9"
System.out.println(v.getQuantity("Cheesy Poofs")); // should print "12"
}
}
当我运行这个以为我一直得到:
true
5.75
8
15
为我出把时我想得到:
true
5.75
9
12
作为我的输出。为什么是这样?我假设它与restockProduct()方法有关,但我似乎无法缩小它的范围,它真的让我很紧张。根据我的CS老师的说法,restockProduct()方法假设将给定数量的指定产品添加到自动售货机,并将尽可能多的物品放入已指定容纳特定产品的第一个槽中使用setProduct())。
如果不是所有的项目都适合第一个插槽,那么尽可能多地将其余部分放入第二个插槽中,以保存该类产品等。对于部分功能,您的方法应该至少能够找到指定的指定产品的第一个时隙,并把所有的项目有”
你的补货方法在做什么与它应该做什么的描述没有相似之处。建议你放弃它并重新开始。 – Dmitri
为什么要打印9?插槽2中应该有3个项目 –