I am new to java programming and I have to write an inventory program that can hold multiple items. I have my code from week 1 but I do not know how to write in the ability to hold multiple inventory items. Can anyone help with this?

You could use an array, matrix (multidimensional array), Vector, List, ArrayList, Collection, Map...
In my opinion, then simplest would probably be to use List<InventoryItem> inventory = new ArrayList<>();

Yes, we can, but we'd need to know what you have done already, or at least what you know how to do. We might need to see your code, or at least the part you are having problems with.

If you need to post part of tyour code, use the Code button on the top of the editing window to paste it it.

In general, for multiple items, you will need either an array, or a collection class such as an ArrayList or HashMap. For this purpose, where you presumably have items with names and a set of properties, a HashMap may be best, as you can then look up the item based on the name. A HashMap is a collection in which a key - for example, the name of the item - is mapped to a value - for example, the item object.

However, since this is an introductory project, I'm guessing they are looking for you to use an array, however. Arrays are the simplest of the compound data structures, being nothing more than a numbered series of elements of a given type. An array is declared like so:

 int[] anArray = new int[5];  // a five-element array of ints
 String[] anotherArray = new String[10] // a 10-element array of Strings

You can then access the elements from 0...n-1 like so:

 anArray[0] = 23;
 anotherArray[4] = "This is the fifth element of the array";

This is probably what you need to use for this assignment, unless your instructor said otherwise.

package cars;
// Robert Sigmon
// 10/12/2014 11:00 AM
public class Cars {

    private final int prodNumber; // product number
    private final String prodName;// product name
    private final int unitsTotal; // total units in stock
    private final double unitPrice; // price per unit

    //initialize four-arguement constructor

    public Cars (int number, String name, int total, double price)
    {
        prodNumber = number;
        prodName = name;
        unitsTotal = total; //validate and store total of cars
        unitPrice = price; // validate and store price per car

    } //end four-arguement constructor

    public int getProdNumber() {
        return prodNumber;
    }   


    public String getProdName() {
        return prodName;
    }


    public int getUnitsTotal() {
        return unitsTotal;
    }


    public double getUnitPrice() {
        return unitPrice;
    }


    public double getValue() {
        return unitsTotal * unitPrice;
    }

} // end class cars

That is the first java file

package cars;
// Robert Sigmon
// 10/12/2014 11:00 AM

public class CarsInventory {


public static void main( String[] args ) {  

//instantiate cars object
Cars product = new Cars(2479, "BMW M6", 45, 65000); 

// get car information
System.out.println("RGS New and Used Car Inventory Program");
System.out.printf( "%s %d\n", "Product Number:", product.getProdNumber() );
System.out.printf( "%s %s\n", "Product Name:", product.getProdName() );
System.out.printf( "%s %d\n", "Total Units in Stock:", product.getUnitsTotal() );
System.out.printf( "%s $%.2f\n", "Price Per Unit:", product.getUnitPrice() );
System.out.printf( "%s $%.2f\n", "Inventory Value:", product.getValue() ); // printing of inventory value

} // end main method
} // end class CarsInventory

That is the second file

Where would I put the Array?

You would presumably replace

    Cars product = new Cars(2479, "BMW M6", 45, 65000); 

with

    Cars[] products = new Cars[10];  // or however large the lot is supposed to be

You would then have to initialize each of the elements with the Cars() constructor:

   products[0] = new Cars(2479, "BMW M6", 45, 65000);
   products[1] = new Cars(2480, "Nissan Leaf", 23, 35000);
   products[2] = new Cars(2481, "Ford Focus", 17, 20000);

And so on like that. You could then put the part which you had on lines 15-19 in a for() loop to print out the information about the different car models.

Could you show me an example of the for() loop please I am having a little trouble understanding

A standard for() loop is used to repeat something a fixed number of times, with one variable - the index - changing on each iteration. It is similar to an if() or while(), except that the conditional has three parts: the initializer, the condition, and the iterator. An example looks like this:

 for( int i = 0; i < anArray.length; i++) {
      System.out.println(anArray[i]);
 }

How this works is, it first initializes the index, i, to zero. Then, it sees if i is less than the length of anArray; if it is, it prints anArray[i]. When the body of the loop is done, it adds one to i (that's what the i++ part does). It then goes back and checks of i < anArray.length, and if it is, it continues that way until i is no longer less than anArray.length.

Now on lines 17 thru 23 I have an error that says cannot find symbol this is without the array

I'd have to see the code that's having the problem to be able to tell you the answer, I'm afraid. Without that, all I could do is guess. What symbol is it saying it can't find?

package cars;
// Robert Sigmon
// 10/12/2014 11:00 AM

public class CarsInventory {


public static void main( String[] args ) {  

//instantiate cars object
     Cars[] products = new Cars[3];

      products[0] = new Cars(2479, "BMW M6", 45, 65000);
   products[1] = new Cars(2480, "Nissan Leaf", 23, 35000);
   products[2] = new Cars(2481, "Ford Focus", 17, 20000);

// get car information
System.out.println("RGS New and Used Car Inventory Program");
System.out.printf( "%s %d\n", "Product Number:", products.getProdNumber() );
System.out.printf( "%s %s\n", "Product Name:", products.getProdName() );
System.out.printf( "%s %d\n", "Total Units in Stock:", products.getUnitsTotal() );
System.out.printf( "%s $%.2f\n", "Price Per Unit:", products.getUnitPrice() );
System.out.printf( "%s $%.2f\n", "Inventory Value:", products.getValue() ); // printing of inventory value

} // end main method
} // end class CarsInventory

It is line 17- 23

Ah, OK, I think I see the problem here. When you are working with arrays, you need to use the array index to indicate which element of the array you want, for example:

System.out.printf( "%s %d\n", "Product Number:", products[0].getProdNumber() );

Note the [0] part: that's the array index, which says, "get the zeroth element of the array" (array indices start at zero and got to n - 1 for a size n array).

OK, now here's the important part: you can have an int variable as the array index value as well. This is useful because you can take what I showed you with the for() loop and put your printf() lines inside the loop, such that the loop index becomes the array index. So if you have a for() loop:

    // get car information
    System.out.println("RGS New and Used Car Inventory Program");

    for(int model = 0; model < products.length; model++) 
        System.out.printf( "%s %d\n", "Product Number:", products[model].getProdNumber() );
        // put the rest of your printf()s here

    }

and do the same with thr rest of the lines, you can loop through the array to get them all.

Here's a simple example to underline what Schol-R-LEA has already said:

public class Item
{
    // Item properties:
    private int _id;
    private String _name;

    // We have a constructor to setup this item:
    public Item(int aNumber, String aName) 
    {
        _id = aNumber;
        _name = aName;
    }

    // The following are "getter" methods:
    public int getID() { return _id; }
    public String getName() { return _name; }

    // We could also have "setter" methods, for setting property changes:
    public void setID(int id) { _id = id; }
    public void setName(String name) { _name = name; }

    // We could also have a printer method:
    public void debugPrintThisItem()
    {
        System.out.println("Item ID: " + _id);
        System.out.println("Item Name: " + _name);
    }
} // End of Item Class

And now the Handler class (with main()):

public class ItemInventoryHandler {
    public static void main(String[] args) {
        Item[] inventory = new Item[10];            // Our inventory database

        // Adding items to inventory:       
        for (int i = 0; i<10; i++) {
            String tmpName = "Name_" + i;           // Generate names
            inventory[i] = new Item(i, tmpName);    // Add new Item to inventory array
        }

        // Now let's print them out:
        for (int i2 = 0; i2 < 10; i++) {         // For each index 0 to 10 (but not including 10)
            // To print them out, I just call the printer method on each instance in the arry:
            inventory[i].debugPrintThisItem();      // Print this item
        }

        // And another way to do this (might need java 7 or above, can't remember):
        for (Item it : inventory) {                 // For each item:
            it.debugPrintThisItem();                // print it
        }
    } // end of main
} // End of class

Hope my comments doesn't wreck readability (Should have some preview post function in this forum)

As I said before, this is only an example (could be some typos here and there), but it is meant as a complete example of what Schol-R-LEA already has pointed out.

package cars;
// Robert Sigmon
// 10/12/2014 11:00 AM

public class CarsInventory {


public static void main( String[] args ) {  

//instantiate cars object
     Cars[] products = new Cars[3];

      products[0] = new Cars(2479, "BMW M6", 45, 65000);
   products[1] = new Cars(2480, "Nissan Leaf", 23, 35000);
   products[2] = new Cars(2481, "Ford Focus", 17, 20000);

// get car information
System.out.println("RGS New and Used Car Inventory Program");

    for (Cars product : products) {
        System.out.printf("%s %d\n", "Product Number:", product.getProdNumber());
    }
    int model = 0;
System.out.printf( "%s %s\n", "Product Name:", products[model].getProdName() );
System.out.printf( "%s %d\n", "Total Units in Stock:", products[model].getUnitsTotal() );
System.out.printf( "%s $%.2f\n", "Price Per Unit:", products[model].getUnitPrice() );
System.out.printf( "%s $%.2f\n", "Inventory Value:", products[model].getValue() ); // printing of inventory value

} // end main method
} // end class CarsInventory

Like this? This runs however it just shows the product number and not the names of the other two items in the inventory. Any ideas what I am missing? Also if I remove the bracket on line 22 it loops however it gives different product numbers but the same print just the BMW M6

The loop to print all the Cars terminates on line 22, so it includes printing the number, but excludes the rest of the prints.

Ok so what changes do I need to make?

I moved the bracket under everything and it loops but it changes the product number but it keeps the first product name and ammounts. Why is that?

I could really use some more help with this as the assignment is due today. Thank you all for your help so far.

I see you've changed to a different type of for() loop, which also changes how data is accessed. Change the references inside the loop back from products[model] to just product, so it is referring to the iterated object.

That worked thank you all for your help.

schol-r-lea, you were a big help with helping me to understand how exactly I would go about changing my program when you explained this,...
You would presumably replace

Cars product = new Cars(2479, "BMW M6", 45, 65000); 

with

Cars[] products = new Cars[10];  // or however large the lot is supposed to be

You would then have to initialize each of the elements with the Cars() constructor:

products[0] = new Cars(2479, "BMW M6", 45, 65000);
products[1] = new Cars(2480, "Nissan Leaf", 23, 35000);
products[2] = new Cars(2481, "Ford Focus", 17, 20000);

This was exactly what I didnt understand and I wasn't understanding the correlation from the text examples to what I have written from my last weeks assignment. Thank you soooooo much! You saved me!

Veronica

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.