DIowa
DIowa

Reputation: 9

Trouble printing objects in ArrayList using Enhanced For Loop

I cannot get the Product Objects to print out anything using an Enhanced for loop. Everything comes out null or 0?

The output show this?

0null0.0This is the id
0null0.0This is the id
0null0.0This is the id

Here's my code:

class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        ArrayList < Product > store1 = new ArrayList < Product > ();
        store1.add(new Product(3, "Nike", 300.0));
        store1.add(new Product(2, "Addidas", 400.0));
        store1.add(new Product(6, "Under Armor", 500.0));
        for (Product y: store1) {
            System.out.println(y + "This is the id");
        }
    }
}

class Product {
    public int id;
    public String name;
    public double price;
    public Product(int startId, String startName, double startPrice) {
        startId = id;
        startName = name;
        startPrice = price;
    }
    public int getId() {
        return id;
    }
    public double getPrice() {
        return price;
    }
    public String getName() {
        return name;
    }
    public String toString() {
        return id + name + price;
    }
}

Upvotes: 1

Views: 56

Answers (3)

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

You are setting the variables the wrong way around in your constructor, i.e.

startId = id; should be id = startId;

You should also add @Override to your toString() method.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074038

You have your assignments backward in the constructor. It should be:

public Product(int startId, String startName, double startPrice) {
    id = startId;       // Not `startId = id;`
    name = startName;   // Not `startName = name;`
    price = startPrice; // Not `price = startPrice;`
}

or better yet (and this would have flagged the problem up for you when you tried to compile), don't rely on implicit this:

public Product(int startId, String startName, double startPrice) {
    this.id = startId;
    this.name = startName;
    this.price = startPrice;
}

Upvotes: 1

You are doing a backward assignments in the constructor:

public Product(int startId, String startName, double startPrice) {
        startId = id;
        startName = name;
        price = startPrice;
    }

leaving the object uninitialized...

but you mean for sure

public Product(int startId, String startName, double startPrice) {
        id = startId;
        name = startName;
        startPrice = price;
    }

Upvotes: 2

Related Questions