【问题标题】:Inventory program in javajava中的库存程序
【发布时间】:2016-06-04 06:46:31
【问题描述】:

大家好,我正在制作一个库存程序,但我在使用 stockItem 删除方法时遇到了问题。我希望它删除给定索引处的项目并返回已删除的项目。如果索引无效则返回null。

到目前为止,这是我的代码。请滚动到底部看看我在说什么。

import java.util.ArrayList;

public class Inventory {
    private ArrayList<StockItem> stock;

    public Inventory() {
        stock = new ArrayList<StockItem>();
    }

    public void addStockItem(StockItem item) {
        stock.add(item);
    }

    public int size() {
        return stock.size();
    }

    public String toString() {
        String result = "";
        for(StockItem item: stock)
            result+=item.toString()+"\n";
        return result;
    }

    public boolean isValidIndex(int index) {
        return index >=0 && index < stock.size();
    }


    public StockItem getItem(int index) {
         if (index < 0 || index >= this.stock.size()){
               return null;
         }
         return this.stock.get(index);
    }


     /**
     * 
     * @param index
     * @return null if index is invalid, otherwise
     * remove item at the given index and return the 
     * removed item.
     */
    public StockItem remove(int index) {
        return null; //I need to do this part
    }


}

【问题讨论】:

    标签: java class object inventory


    【解决方案1】:

    可能是这样的:

    /**
     * 
     * @param index
     * @return null if index is invalid, otherwise remove item at the given
     *         index and return the removed item.
     */
    public StockItem remove(int index) {
        if (index >= 0 && index < stock.size()) // check if this index exists
            return stock.remove(index); // removes the item the from stock   and returns it
        else
            return null; // The item doesn't actually exist
     }
    

    还有一个使用对象删除的示例:

    public boolean remove(StockItem item) {
        if (item != null && stock != null && stock.size() != 0)
            return stock.remove(item);
        else
            return false;
    }
    

    【讨论】:

    • stock.remove(index) 移除并返回被移除的元素,因此您无需先获取元素即可移除它。
    【解决方案2】:

    您需要迭代列表中的所有项目,当您找到需要删除的项目的匹配项时..您可以删除该特定项目..

    迭代该列表的 for 循环并比较...

    【讨论】:

      【解决方案3】:

      使用您已经声明的方法,代码可以是这样的:

      public StockItem remove(int index) {
          // if the index is valid then remove and return the item in given index
          if(isValidIndex(index)){
              return this.stock.remove(index);
          }
      
          //return null otherwise
          else{
              return null;
          }
      } 
      

      ArrayList 中的 remove 方法删除给定索引处的项目并返回已删除的项目。请阅读ArrayList 的文档以获取更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-10
        • 2020-02-14
        • 2014-07-16
        • 2022-06-10
        • 2018-04-10
        相关资源
        最近更新 更多