亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何編寫 GetItemIndex 方法

如何編寫 GetItemIndex 方法

LEATH 2022-10-20 15:07:53
我正在創建一個代表購物車的 ShoppingCart 類。我對類的基礎知識和 getTotalPrice 方法很了解,但我無法弄清楚如何解決 getItemIndex 問題...“完成 getItemIndex 方法如下:如果 itemList 有一個名稱傳遞給參數的項目,返回該項目在數組中的索引。否則返回 -1。"我知道我必須調用 Items 類,但我不明白如何從項目類中獲取名稱并返回索引。我已經創建了 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     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條經驗 獲得超6個贊

這應該有效。您指定要查找的 nameOfItem。然后遍歷數組中的所有項目,如果它在數組中,則返回索引。


int getItemIndex(String nameOfItem){

   for(int i = 0; i < itemList.length; i++){

      if(itemList[i].getName().equals(nameOfItem){

         return i;

      }

   }

   return -1;


查看完整回答
反對 回復 2022-10-20
  • 1 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號