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:)
#call objects in for loop
1 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @dusky mantle! Please use
/closeor theClose Postbutton 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.
not sure what you mean by this. if you want to create a new Produce 10 times you don't need the index. if you want to store the objects somewhere you can do that by adding 10 Products to a list or another data structure.
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
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
Thank you very much guys !