How to create array from a class constuctor?

2019-08-31 07:18发布

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.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-31 08:13

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();
    }
}
查看更多
不美不萌又怎样
3楼-- · 2019-08-31 08:17

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
查看更多
三岁会撩人
4楼-- · 2019-08-31 08:24

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:

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

查看更多
登录 后发表回答