我正在創(chuàng)建一個代表購物車的 ShoppingCart 類。我對類的基礎(chǔ)知識和 getTotalPrice 方法很了解,但我無法弄清楚如何解決 getItemIndex 問題...“完成 getItemIndex 方法如下:如果 itemList 有一個名稱傳遞給參數(shù)的項目,返回該項目在數(shù)組中的索引。否則返回 -1。"我知道我必須調(diào)用 Items 類,但我不明白如何從項目類中獲取名稱并返回索引。我已經(jīng)創(chuàng)建了 Items 類以及 ShoppingCart 類的實例變量和構(gòu)造函數(shù)。我查看了其他購物車方法,但找不到執(zhí)行 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 cartprivate 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;} }
1 回答

慕妹3242003
TA貢獻1824條經(jīng)驗 獲得超6個贊
這應(yīng)該有效。您指定要查找的 nameOfItem。然后遍歷數(shù)組中的所有項目,如果它在數(shù)組中,則返回索引。
int getItemIndex(String nameOfItem){
for(int i = 0; i < itemList.length; i++){
if(itemList[i].getName().equals(nameOfItem){
return i;
}
}
return -1;
}
添加回答
舉報
0/150
提交
取消