COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

ArrayList ArrayListProcessing.java NameSearching.java Hardware Store Program With ArrayList MyArrayList Program
MyArrayList.java
MyArrayListClient.java




Hardware Store with ArrayList Program


Description

The program defines a class Inventory to represent hardware store product and uses an ArrayList to organize Inventory objects.

The program reads an external data file which contains the inventory data to populate the ArrayList.

The users can print the inventory, search a particular product, calculate the total value of inventory, and etc.

Define Inventory class

Read external data file to fill in the ArrayList with Inventory objects

Print the inventory

Calculate the value of total inventory

Find the inventory with the highest value

Search a particular inventory in the ArrayList


This problem was originally presented as an exercise in C++ HOW TO PROGRAM (2nd Edition) book.
Exercise 14.12 (Page 738). Authors: Deitel & Deitel
The requirements are revised to meet our purpose.


Associated Concepts:

ArrayList

Algorithm:

Inventory class diagram:



Client program:

Create an ArrayList of Inventory

Use JFileChooser object to select the data file

Call populateArrayList method

Use loop and switch structures to write a menu driven program.

Call printArrayList method

Call calculateTotal method

Call indexOfHighest method

Call searchItem method

populateArrayList method definition:

Read the top line of data without storing it

Declare variable i and initialize it to 0

while loop: as long as the data file has data item

Read data items from the data file

Create Inventory object and add it to the ArrayList

printArrayList method definition:

For each item in the ArrayList

Print the item

calculateTotal method definition:

Declare variable sum and initialize it to 0

For i = 0 up to the size of the ArrayList

Add the current element's in-stock value at i to sum

return sum

indexOfHighest method definition:

Declare variable maxIndex and assign it to 0 (Assume the first element has the highest in-stock value)

For i = 1 up to the size of the ArrayList

If the in-stock value of current element at i is greater than the highest element

    Update maxIndex to the current index i

return maxIndex

searchItem method definition:

For i = 0 up to the size of the ArrayList

If the current element at i is equal to the searched key

    Found it and return i

If the loop ended without returning i

    Not found and return -1