Ame3n
Ame3n

Reputation: 53

how to create multiple objects through loops in 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?

Upvotes: 5

Views: 7255

Answers (3)

ARB
ARB

Reputation: 327

`ArrayList < Student > StudentList = new ArrayList < Student > (3);
 for (int i = 0; i < 3; i++) {
 Student f = new Student();
 StudentList.add(f);
}
// call object one by one
StudentList.get(0).print("awais", "but1");`

Upvotes: 0

Ali ZD
Ali ZD

Reputation: 100

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();
}

Upvotes: 5

Bernhard
Bernhard

Reputation: 1273

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

Upvotes: 1

Related Questions