I'm learning how to program in java and I'm stuck on how to create multiple objects using loops.
class LaunchFarmer {
public static void main(String[] args) {
for(int i=1;i<=3;i++)
{
Farmer f = new Farmer;
f.input();
f.compute();
f.display();
}
}
}
Now, this will create 3 objects to access the above methods, but I also would like to specify each farmer like farmer 1
, farmer 2
and so on. How can I do that?
You Can add created Objects into a List:
public static void main(String[] args) {
List<Farmer> farmerList = new ArrayList<Farmer>(3);
for(int i=0; i<3; i++) {
Farmer f = new Farmer();
farmerList.add(f);
}
// now call object methods
farmerList.get(0).input();
}
Welcome to Stackoverflow. I don't know of a direct way of doing what you want, not sure if it's possible in Java. Common recommendation is to create an ArrayList for your objects (in your case farmers = new ArrayList<Farmer>()
) and collect your farmer there. Instead of calling them via farmer1, farmer2 ...
you can call them by farmers.get(0)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With