0

This is a program that allows users to add data to a system. This is specifically the invetory class of the program where our task is to convert the object inventory into an object of an array list... I am new to array lists and I would like some assistance figuring this out.

I have tried a few times but have had no luck so far, anything helps!

public class Inventory {
    /**
     * List of FoodItems that represents our inventory
     */
    private FoodItem[] inventory;

    /**
     * Number of items that a user has entered
     */
    private int numItems;

    /**
     * Default Constructor
     */
    public Inventory() {
        inventory = new FoodItem[20];
    }

    /**
     * Reads from the Scanner object passed in and fills the data member fields of the class with valid data.
     * @param scanner - Scanner to use for input
     * @return <code>true</code> if all data members were successfully populated, <code>false</code> otherwise
     */
    public boolean addItem(Scanner scanner) {

        if(numItems == 20)
        {
            System.out.println("Inventory full");
            return false;
        }
        boolean valid = false;
        FoodItem item = null;
        while(!valid)
        {
            System.out.print("Do you wish to add a fruit(f), vegetable(v) or a preserve(p)? ");
            if(scanner.hasNext(Pattern.compile("[fFvVpP]")))
            {
                String choice = scanner.next();
                switch(choice.toLowerCase())
                {
                case "f":
                    item = new Fruit();
                    break;
                case "v":
                    item = new Vegetable();
                    break;
                case "p":
                    item = new Preserve();
                    break;
                default: // Should not get here.
                    item = new FoodItem();
                    break;
                }
                valid = true;
            }
            else
            {
                System.out.println("Invalid entry");
                scanner.next();
                valid = false;
            }
        }
        if(item.inputCode(scanner))
        {
            if(alreadyExists(item)<0)
            {
                if(item.addItem(scanner))
                {
                    inventory[numItems] = item;
                    numItems++;
                    return true;
                }
                return false;
            }
            else
            {
                System.out.println("Item code already exists");
                return false;
            }
        }
        return true;
    }

    /**
     * Search for a food item and see if it is already stored in the inventory
     * @param item - FoodItem to look for
     * @return - The index of item if it is found, -1 otherwise
     */
    public int alreadyExists(FoodItem item) {
        for(int i=0;i<numItems;i++)
        {
            if(inventory[i].isEqual(item))
                return i;
        }
        return -1;
    }

    /**
     * Update the quanity stored in the food item
     * @param scanner - Input device to use 
     * @param buyOrSell - If we are to add to quantity (<code>true</code>) or remove (<code>false</code>)
     * @return
     */
    public boolean updateQuantity(Scanner scanner, boolean buyOrSell) {
        // If there are no items then we can't update, return
        if(numItems == 0)
            return false;

        FoodItem temp = new FoodItem();
        temp.inputCode(scanner);
        int index = alreadyExists(temp);
        if(index != -1)
        {
            String buySell = buyOrSell?"buy":"sell";
            System.out.print("Enter valid quantity to "+buySell+": ");
            if(scanner.hasNextInt())
            {
                int amount = scanner.nextInt();
                if(amount > 0)
                {
                    return inventory[index].updateItem(buyOrSell? amount: amount*-1);
                }
                else
                {
                    System.out.println("Invalid quantity...");
                }
            }
            else
            {
                System.out.println("Invalid quantity...");
            }
        }
        return false;
    }

    @Override
    public String toString() {
        String returnString = "Inventory:\n";
        for(int i=0;i<numItems;i++)
            returnString += inventory[i].toString() + "\n";
        return returnString;
    }
}
2
  • What is a... Item, Fruit, Vegetable, Preserve, and FoodItem? Commented Oct 20, 2019 at 4:22
  • These are separate classes in the program, they all extend FoodItem which is the abstract class in this program. Item however is an object that is referenced from FoodItem class. Commented Oct 20, 2019 at 6:54

1 Answer 1

2

I could be misunderstanding the question, but I'm guessing you want to convert Inventory to use an ArrayList, rather than convert it into an ArrayList. Is that correct?

If I understood the question correctly, then the first thing you'll want to do is change the declaration of the inventory field to an ArrayList:

private List<FoodItem> inventory;

Notice that I've declared this as the List interface, rather than the concrete ArrayList implementation. Unless there's a specific feature of the ArrayList implementation you need that's not available in the generic interface, it's usually best to operate at the generic interface level to give yourself the most flexibility.

However, in the constructor, you'll actually instantiate the concrete ArrayList:

public Inventory() {
    inventory = new ArrayList<>(20);
}

By switching from a bare array to an ArrayList, you'll find the first advantage of using a Collection, in that you won't need the alreadyExists() method any longer. List, and its super interface, Collection, supports the contains() method.

This:

if(alreadyExists(item)<0)

becomes:

if (!inventory.contains(item))

...and you can remove the alreadyExists() method.

The second advantage is that you'll no longer need to track the number of items in the inventory as a separate field. List already provides this for you.

This:

if(numItems == 20)

becomes:

if (inventory.size() == 20)

..and you can delete the numItems field from your class.

The third advantage is that List/Collection supports a toString() very similar to the implementation you have above.

This:

   @Override
    public String toString() {
        String returnString = "Inventory:\n";
        for(int i=0;i<numItems;i++)
            returnString += inventory[i].toString() + "\n";
        return returnString;
    }

becomes:

   @Override
    public String toString() {
        return "Inventory:\n" + inventory.toString();
    }

The main difference between your toString() and the toString() provided by List is that you have new lines between each item, and List simply puts commas between each item. If you wanted to keep the new lines, then the looping on List/Collection is a little less cumbersome than arrays:

   @Override
    public String toString() {
        String returnString = "Inventory:\n";
        for(FoodItem item : inventory) {
            returnString += item.toString() + "\n";
        }
        return returnString;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Awsome, thanks for this! However I am still getting some errors on lines 115 and 105. 115: return inventory[index].updateItem(buyOrSell? amount: amount*-1); 105: int index = alreadyExists(temp);
Yes, that's because Lists and arrays are similar, but different data structures with different syntax. Implementations of the List interface are normal objects with fields and methods, and arrays are primitive types. So instead of the inventory[index] syntax, you need to call the inventory.get(int index) method on line 115. On line 105, you would replace your alreadyExists() with inventory.contains(temp) as I demonstrated in the answer. Here's the javadoc for List: docs.oracle.com/javase/8/docs/api/java/util/List.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.