#call objects in for loop

1 messages · Page 1 of 1 (latest)

dusky mantle
#

Hi everyone,
Got a beginner question.
I wanted to print objects in a for loop
(Like in python if I wanted to say
for i in range(1,10):
print(product_i))
In my main I have something like that
for (int i=1;i<10,i++) {
new Product ("p"+i)
Then how am I supposed to print every p_i?
System.out.println("name is"+ p_i.getName() ?
Thanks for your help:)

lilac runeBOT
#

This post has been reserved for your question.

Hey @dusky mantle! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

ruby warren
#

if you want to retrieve these objects there are several ways to do so depending on the data structure. Being more specific is always helpful

high fjord
#

You can call method on constructor

System.out.println(new Product("name" + i).getName());
#

public class demo {
    public static void main(String args[]){
        for(int i = 0; i < 10; i++) {
            System.out.println(new Product(("test" + i), 13).getName());
        }
    }
}

public class Product {
    String name;
    int price;
    
    String getName() {
        return name;
    }
    
    public Product(String inName, int inPrice) {
        name = inName;
        price = inPrice;
    }
}
#

And when I run demo.java I get this

dusky mantle
#

Thank you very much guys !