尝试创建对象数组的ArrayIndexOutOfBoundsException

时间:2019-03-31 01:00:11

标签: java arrays processing

我正在尝试在“对象”类中创建一个对象数组(占位符,因为我尚不知道该如何调用这些对象,),当我尝试运行该程序时会抛出两个异常...

  1. ArrayOutOfBoundsException:0
  2. 无法运行草图(目标VM初始化失败)
objects[] obs;
int count;
void setup(){
  fullScreen();
  background(0);
  textSize(70);
  textAlign(CENTER);
  frameRate(60);
  obs = new objects[count];
int objectNumber;
  int index = 0;
  for(objectNumber = 0;objectNumber <=4;objectNumber++){
   obs[index++] = new objects(random(0,width),random(0,height),2);


  }
}
 /* this is a break from the code(im skipping code that really shouldn't affect this(it doesn't call or edit the array or any previously mentioned variables*/
class objects{
    float objectSpeed = 12;
 float xPos;
 float yPos;
 objects(float tempxPos,float tempyPos, int tempSpeed){
   xPos = tempxPos;
   yPos = tempyPos;
   objectSpeed = tempSpeed;


 }
 void update(){
   yPos = yPos+objectSpeed;


 }
 void Display(){
 fill(255);
ellipse(xPos,yPos,20,20);

 }


}
/* more skipping in the draw block, again doesn't call or edit anything previously declared*/

function draw(){

for(objects ob : obs ){
ob.update();
ob.Display();

}

}

1 个答案:

答案 0 :(得分:0)

您发生了几件事。

首先,您忘记给count变量赋值。在Java中,将为该变量分配默认值0。这意味着该行将创建一个大小为0的数组:

obs = new objects[count];

在Java中,数组不可可调整大小。这也意味着您不能这样做:

for(objectNumber = 0;objectNumber <=4;objectNumber++){
  obs[index++] = new objects(random(0,width),random(0,height),2);

您正在尝试添加比数组具有索引更多的元素。这在Java中不起作用。

相反,您需要给数组指定预定义的长度,然后仅使用该长度进行循环。

无耻的自我推广:here是有关数组的教程。您还可以在the Processing reference和Google上找到更多信息。

解决此问题后,您还可以在此处混合使用一些JavaScript语法:

function draw(){

此语法在Java中不起作用。您需要使用返回类型定义函数。具体来说,draw()函数具有void返回类型:

void draw(){

在使用时,请养成遵循标准命名约定和缩进的习惯。变量和函数应以小写字母开头,而类应以大写字母开头。适当地缩进代码可使其更易于阅读,从而更容易帮助您。

我能给您的最好建议是start smaller。从一个简单的Processing草图开始,该草图可以做一些简单的事情,例如显示单个椭圆。然后在其中添加一个小东西,并继续进行小步骤。您一次要尝试做很多事情,据了解,这只会导致头痛。

最后,请不要侮辱自己。做某事的初学者很好。我强烈建议编辑您的帖子,以删除帖子中您自称名字的地方。

祝你好运。