How to create array from a class constuctor?

2019-08-31 07:44发布

问题:

So basically I have a class with my program and it's constructing rain elements for my animation. I was wondering how can I use arrays to create say 50 objects from this class but at the same time alternate the data in the objects.

 void setup()
  {
   size (400,400);
   noStroke();
   rain = new Rain(20,random(0,10),3,15);
   rain2 = new Rain(random(15,35), random(70,110),3,15);

  }
 void draw()
  {
   background(0);
   rain.colour(125,155,100);
   rain.display();
   rain2.colour(125,155,100);
   rain2.display();
  }

This is what I'm using to create 2 rain droplets; as I said how can I get arrays to create multiple objects but keep randomizing the data in the constructor?

Here's the constructor incase your wondering and yes I'm very new to classes and java itself.

回答1:

You create an instance of a class when you use its constructor. You can store instances inside an array.

So really you've got two issues: creating 50 instances of your class, and adding those instances to an array.

You can solve the first problem using a for loop, and you solve the second problem by using an array:

Rain[] rainDrops = new Rain[50];
for(int i = 0; i < 50; i ++){
   Rain rain = new Rain(random(100), random(100),3,15);
   rainDrops[i] = rain;
}

Notice that you might base the values you pass into the random() function on your loop variable i, depending on exactly what you want to happen.

Then you can loop through that array to draw every single instance in your array:

for(Rain r : rainDrops){
  r.display();
}

You could also use an ArrayList for this, if you don't want to specify the number of instances ahead of time.

More info in the Processing reference:

  • Array
  • for
  • ArrayList

Shameless self-promotion: I've written tutorials on using arrays and objects in Processing available here and here.



回答2:

50 objects:

Rain obj[]=new Rain[50];

void setup() {

iterate with a loop: for (int i; ...) : exercise

Constructor:

public class Rain {
    public Rain(int a, int b, int c, int d)
    {
    // Do your random ... : exercice

    }

draw:

void draw()
{
// iterate : exercice


回答3:

Create an arraylist, then populate the list with randomly generated Rain objects. Later, iterate through the arraylist to color and display them.

ArrayList<Rain> rainObjects;

void setup()
{
    size (400,400);
    noStroke();
    rainObjects = new ArrayList<Rain>();
    for (int i=0; i<numberOfRainObjectsYouWant; i++)
    {
        // Create Rain object with random parameters
        Rain rain = new Rain(/* Random parameters using the random() method */);
        rainObjects.add(rain);
    }
}

void draw()
{
    background(0);
    for (Rain rain : rainObjects)
    {
        rain.colour(125,155,100);
        rain.display();
    }
}