5

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?

3 Answers 3

5

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that arrays and Lists number from 0 in java so people tend to do their loops in the style int i=0; i<3; i++ rather starting from 1.
@Tom oh yes, Thanks for the mention.
1

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

Comments

0
`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");`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.