user6408795 user6408795 - 6 months ago 18
Java Question

Inventory program in java

Hi guys I am making an inventory program and I am having trouble with the stockItem remove method. I want it to remove item at the given index and return the removed item. And return null if the index is invalid.

This is my code so far. Please scroll to the bottom to see what I'm talking about.

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
}


}

Answer

It could be something like this:

/**
 * 
 * @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
 }

And one example removing using object:

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