如何创建从类constuctor阵列? [英] How to create array from a class constuctor?

查看:353
本文介绍了如何创建从类constuctor阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有我的计划一类,它的构造雨元素我的动画。我不知道我该如何使用数组创建说,从50个对象这一类,但在同一时间交替中的对象的数据。

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

这是我使用创建2雨滴的东西;我说我怎么能得到阵列创建多个对象,但保留随机在构造函数中的数据?

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?

下面是柜面你想知道的构造是的,我很新的类和Java本身。

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

推荐答案

当你使用它的构造函数创建一个类的例如。您可以存储阵列内部的情况。

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

所以真的你有两个问题:创建类的50个实例,并将这些实例的数组

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

请注意,你可能会立足于您的循环变量 传递到随机()函数的值I ,这取决于你希望发生什么。

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

您也可以使用的ArrayList 此,如果你不想提前指定实例的数量。

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

加工参考

  • Array
  • for
  • ArrayList

无耻的自我推销:我已经写了关于使用数组和对象的处理提供这里这里

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

这篇关于如何创建从类constuctor阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆