Я пытаюсь запрограммировать программу, которая имитирует действия торгового автомата для моего класса CS. У меня есть запас двойного массива, который представляет количество элементов в определенном «слоте» [мой торговый автомат странный и похож на один длинный торговый автомат с 1 столбцом разных товаров]. Вот мой код до сих пор:Почему я продолжаю получать исключение 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
}
}
Каждый раз, когда я runException в потоке "основного" java.lang.ArrayIndexOutOfBoundsException: 0 в VendingMachine.setProduct (VendingMachine.java:27) в vmd.main (VMD. java: 9) этот код, хотя я получаю это сообщение об ошибке:
Может кто-то здесь объяснить мне, почему я продолжаю эту ошибку? Я имею в виду, что логика кажется вполне правильной.
поэтому у вас есть ошибка, исходящая от вашей основной функции, но вы не собираетесь включать ее в свой код? –