对象数组NullPointerException,处理3.3.6 [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在尝试在Processing中制作一个简单的3D游戏,但我遇到了一个问题。我试图创建一个数组来跟踪我的环境对象并使其更容易修改。但是,当我尝试运行该程序时,它将无法正常工作。

主要代码:

  //arrays
BoxCl[] envArr;

void setup() {
  size(640, 360, P3D);

  envArr[0] = new BoxCl(1,1,-1,1);              //it shows the error here
  envArr[envArr.length] = new BoxCl(2,1,-1,1);
}

void draw() {
  background(0);
  camera(mouseX, height/2, (height/2) / tan(PI/6), width/2, height/2, 0, 0, 1, 0);
  Update();
  Draw();
}

void Update(){

}

void Draw(){
  for(BoxCl i : envArr){
    i.Draw();
  }
}

BoxCl类:

class BoxCl{

  float x, y, z;
  int s;

  BoxCl(float x, float y, float z, int size){
    this.x = x;
    this.y = y;
    this.z = z;
    this.s = size;
  }

  void Draw(){
    translate(scale*x, scale*y, scale*z);
    stroke(255);
    fill(255);
    box(s * scale);
    translate(scale*-x, scale*-y, scale*-z);
  }

}

我已经尝试过了(here for example),但我觉得我太缺乏经验,无法理解我应该做些什么。

请帮忙。

编辑:我知道应该在使用之前定义变量/数组/对象。但是我如何以一种它仍然可以改变的方式定义envArr? (即当我必须创建或删除对象时增加或减小大小)

java arrays object nullpointerexception processing
1个回答
1
投票

你的envArr变量是null。在使用之前,您必须将其初始化为某些内容。

你可能想要这样的东西:

BoxCl[] envArr = new BoxCl[10];

无耻的自我推销:我在Processing available here上写了一个关于数组的教程。您还应该通过添加debugging your code语句或使用调试器逐步执行代码来养成println()的习惯。例如,如果你在抛出错误的行之前打印出envArr的值,那么你自己就会看到它是null

© www.soinside.com 2019 - 2024. All rights reserved.