我正試圖編寫一個程序來模擬CS類的自動售貨機的操作。我有一個雙數組庫存,它表示特定「插槽」中的物品數量[我的自動售貨機很奇怪,有點像一臺自動售貨機,有一列不同的物品]。這是我到目前爲止的代碼:爲什麼我繼續得到ArrayIndexOutofBoundsException?
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][0];
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 currentCapacity = quantity - maxPerSlot;
for(int i = 0; i < stock.length; i++){
if (itemName[i]==Product){
for(;quantity <= maxPerSlot && currentCapacity != 0; quantity--)
stock[i][0] += 1;
}
}
//Put # of products in slot that holds it and if that slot is full put the rest in the next
//availble 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][1]; // 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 += stock[i][1];
}
}
return total;
}
public boolean buyItem(int slot)
{ int snum = slot;
if (stock[snum][1] != 0){
stock[snum][1]--;
return true;
} else {
return false;} // replace this line with your code
}
}
每次我在線程 「主要」 java.lang.ArrayIndexOutOfBoundsException runException:0 在VendingMachine.setProduct(VendingMachine.java:27) 在vmd.main(VMD。 java:9)這段代碼雖然我得到這個錯誤信息:
有人可以在這裏請向我解釋爲什麼我繼續得到這個錯誤?我的意思是邏輯看起來非常正確。
所以你有一個錯誤來自你的主函數,但你不打算將它包含在你的代碼中? –