-1

This is my school assignment. I need an inventory system which auto-updates product ID when users key-in a new product. I created an array of object named Product with 4 attributes(name,ID,price,quantity). The ID should not need a user input.

This part is in the input() method,which is in a different class from the Object.I didn't pass the ID to the object class like I did to the other three attributes.

            x[i] = new Product(name,price,stock);
            id = x[i].setID();   

part of the object class:

/**
 * Constructor
 */
public Product(){
    id = 0; name = ""; price = 0.00; quantity = 0;
}

public Product( String n, double p, int q){
    setName(n); setPrice(p); setQuantity(q);
}

public void setID(){
    this.id = id++;
}

Thank you.

shunmin
  • 1
  • 2
  • Are you looking for a way to auto-generate IDs? – sbrattla Mar 17 '13 at 10:26
  • The idea is increasing the id every time a new Product added, so you can just create a COUNT that will be increased every time you enter new product and set id to the id in the Product Class – Azad Mar 17 '13 at 10:30

2 Answers2

1

What you have won't work, because id is an instance variable. This means that every product you create will have an ID of 0. And calling setID() on every product you create will set the ID of avery product to 1.

You need a static counter, which would belong to the class, and not to each of its instances:

public class Product {
    private static int nextId = 0;

    ...

    public Product(String name, double price, int quantity) {
        this.id = Product.nextId;
        Product.nextId++;
        this.name = name; 
        this.price = price; 
        this.quantity = quantity;
    }
}

Note that this wouldn't work well in a multi-threaded environment, and that double is a bad choice for prices, but you'll learn that later.

See the Java tutorial for more information about instance and static variables.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Are you looking for a way of generating a unique id for each Product object? If so, the way you've coded it now doesn't work, because each Product has its own id, which is completely independent of all other Product objects. There are a couple of ways you could approach this:-

  1. Look into what static variables mean in Java
  2. Maintain a variable in your code that gets incremented every time you create a Product object. Pass this variable into the constructor of Product.
Andrew Fielden
  • 3,751
  • 3
  • 31
  • 47