第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何編寫 GetItemIndex 方法

如何編寫 GetItemIndex 方法

LEATH 2022-10-20 15:07:53
我正在創(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;


查看完整回答
反對 回復(fù) 2022-10-20
  • 1 回答
  • 0 關(guān)注
  • 88 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號