Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create multiple objects through loops in java

Tags:

java

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?

like image 766
Ame3n Avatar asked Mar 05 '23 12:03

Ame3n


2 Answers

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();
}
like image 170
Ali ZD Avatar answered Mar 17 '23 09:03

Ali ZD


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)...

like image 39
Bernhard Avatar answered Mar 17 '23 10:03

Bernhard