Я создаю класс ShoppingCart, представляющий корзину покупок.Я хорошо разбираюсь в основах класса и метода getTotalPrice, но не могу понять, как решить проблему getItemIndex ... "Завершите метод getItemIndex следующим образом: если itemList имеет элемент с именем, переданным в параметр,вернуть индекс этого элемента в массиве. В противном случае вернуть -1. "
Я знаю, что должен вызвать класс Items, но я не понимаю, как я могу получить имя из класса item и вернутьиндекс.
Я создал класс Items, переменные экземпляра и конструктор класса ShoppingCart.Я посмотрел на другие методы корзины покупок, но я не смог найти тот, который делает getItemIndex
. Я попробовал код, включенный в нижней части, называется getItemIndex ... Я включил getTotalPrice на случай, если это необходимо в качестве ссылки,
public class ShoppingCart{
private Items[] itemList;
//TODO: declare the number of distinct items in the cart
private int numItems = 0;
private static final int INITIAL_CAP = 5; // the initial size of the
cart
private static final int GROW_BY=3;
// ---------------------------------------------------------
// Creates an empty shopping cart with a capacity for 5 items.
// ---------------------------------------------------------
public ShoppingCart(){
itemList = new Items[INITIAL_CAP];
numItems = 0;
}
public double getTotalPrice(){
double totalPrice = 0;
numItems = 0;
for(int i = 0; i<itemList.length; i++){
if(itemList[i]!= null){
totalPrice = totalPrice + (itemList[i].getQuantity()*itemList[i].getPrice());
numItems++;
}
}
return totalPrice;
}
private int getItemIndex(){
if(itemList(itemList.getName))
return Items[itemList.getName];
else
return -1;
}
}
Вот класс элементов
public class Items{
private String name;
private double price;
private int quantity;
public Items (String n, double p, int q){
name = n;
price = p;
quantity = q;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public int getQuantity(){
return quantity;
}
public void addQuantity(int amt){
int newQuantity = amt + quantity;
quantity = newQuantity;
}
public String toString(){
return "item name: " + name + ", item quantity: " + quantity + ", total price: " + (price * quantity);
}
}
Я ожидаю, что метод, который является оператором if, но яЯ не уверен, как получить ItemIndex ... Я не уверен, если это требует цикла for либо.В другом классе я назову этот метод, чтобы использовать его для моделирования покупок.