How to loop through objects?

Let’s say that we have a simple class in use here:

boolean wheatClicked = false;
boolean carrotClicked = false;
boolean potatoClicked = false;

class Crop
{
  int quantity;
  
  Crop(int cropQuantity)
  { 
    quantity = cropQuantity;
  }
  
  void IncrementData()
  {
    quantity += 1;
  }

  wheatClicked = false;
  carrotClicked = false;
  potatoClicked = false;
}

Crop wheat;
Crop carrot;
Crop potato;

void setup()
{ 
  wheat = new Crop(1);
  carrot = new Crop(5);
  potato = new Crop(10);
}

void draw()
{ 
  if (wheatClicked)
    wheat.IncrementData();
  if (carrotClicked)
    carrot.IncrementData(); 
  if (potatoClicked)
    potato.IncrementData();
}

void mousePressed()
{ 
  if (mouseX > 100 && mouseX < 150)
  {
    if (mouseY > 250 && mouseY < 300)
      wheatClicked = true;
    if (mouseY > 350 && mouseY < 400)
      carrotClicked = true;
    if (mouseY > 450 && mouseY < 500)
      potatoClicked = true;
  }
}

However, there won’t be just 3 crops, there will be dozens. So do I have to physically write out dozens of dozens of lines of repetitive code? Or can I loop these in perhaps a for loop or something?

And if so, how would I do so?

Thanks

1 Like

Yes. Instead of having one object for each of your crops, put all your crops in an array. It’s like a list of them.

Becomes just:

Crop[] crops = new Crop[12];

Now you suddenly have space for a dozen Crop objects! Next, use a loop to create them. Since this only happens once, do it in setup():

for( int i = 0; i < crops.length; i++){
  crops[i] = new Crop(0);
}

Now you can loop over them in draw() too, to draw them.

BONUS THOUGHT: Can you write a function in the Crop class that detects if a mouse was clicked on that crop? The Crop class will need to know a few things about itself… like its position…

See also: Arrays / Processing.org

2 Likes

Cool! Thanks!

Oh and yes, I can do stuff with mousePressed and all that. This was just a short snippet I created.

Oh, and a quick question… so after I do this:

for(int i = 0; i < crops.length; ++i)
  crops[i] = new Crop(5);

Then I can do this?

crops[0].IncrementData();
1 Like

Yes, exactly. You pick one of the crops out of the list by using the square brackets [] with an index, and then you call the function on that crop object.

2 Likes

Cool, thanks! :ok_hand: