Since you are creating a new Laptop
on each pass of your loop, you're getting identical objects each time. Unless you set the fields in your Laptop
class, you won't see different data between them.
Instead, your Laptop
class needs to have it's fields set, either in the constructor (when creating each Laptop
), or via setters.
Here's a quick and simple demo application you can try out and see it in action:
class LaptopDemo {
public static void main(String[] args) {
// First, create some sample laptops and add them to an Array
Laptop[] laptops = new Laptop[5];
// You need to create a new laptop and set it's field values
laptops[0] = new Laptop("HP", 400.00, 100, 6);
laptops[1] = new Laptop("HP", 800.00, 80, 8);
laptops[2] = new Laptop("Dell", 300.00, 150, 6);
laptops[3] = new Laptop("Dell", 680.00, 100, 8);
laptops[4] = new Laptop("Toshiba", 350.00, 60, 4);
// Now you can loop through the array and print the details
for (int i = 0; i < laptops.length; i++) {
// Build the String to be printed
StringBuilder sb = new StringBuilder();
sb.append("Manufacturer: ").append(laptops[i].getManufacturer()).append(", ")
.append("Price: $").append(laptops[i].getPrice()).append(", ")
.append("Hard Drive: ").append(laptops[i].getHdCapacity()).append("GB, ")
.append("RAM: ").append(laptops[i].getRamCapacity()).append("GB");
System.out.println(sb.toString());
}
}
}
class Laptop {
private final String manufacturer;
private final double price;
private final int hdCapacity;
private final int ramCapacity;
public Laptop(String manufacturer, double price, int hdCapacity, int ramCapacity) {
this.manufacturer = manufacturer;
this.price = price;
this.hdCapacity = hdCapacity;
this.ramCapacity = ramCapacity;
}
public String getManufacturer() {
return manufacturer;
}
public double getPrice() {
return price;
}
public int getHdCapacity() {
return hdCapacity;
}
public int getRamCapacity() {
return ramCapacity;
}
}
Results:
Manufacturer: HP, Price: $400.0, Hard Drive: 100GB, RAM: 6GB
Manufacturer: HP, Price: $800.0, Hard Drive: 80GB, RAM: 8GB
Manufacturer: Dell, Price: $300.0, Hard Drive: 150GB, RAM: 6GB
Manufacturer: Dell, Price: $680.0, Hard Drive: 100GB, RAM: 8GB
Manufacturer: Toshiba, Price: $350.0, Hard Drive: 60GB, RAM: 4GB