如何编写 GetItemIndex 方法

How to write GetItemIndex method

我正在创建一个代表购物车的 ShoppingCart class。我擅长 class 和 getTotalPrice 方法的基础知识,但我不知道如何解决 getItemIndex 问题... "Complete the getItemIndex method as follow: if the itemList has an item with the name passed into the parameter, return the index of that item in the array. Otherwise return -1. "

我知道我必须调用项目 class,但我不明白如何从项目 class 和索引 return 中获取名称。

我已经创建了 Items class 以及 ShoppingCart class 的实例变量和构造函数。我查看了其他购物车方法,但找不到执行 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;
} 

}

这是项目class

     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 循环。在另一个class中,我将调用此方法来使用它来模拟购物体验。

这应该有效。您指定要查找的 nameOfItem。然后遍历数组中的所有项目,如果它在数组中,returns 索引。

int getItemIndex(String nameOfItem){
   for(int i = 0; i < itemList.length; i++){
      if(itemList[i].getName().equals(nameOfItem){
         return i;
      }
   }
   return -1;
}