【问题标题】:Object array NullPointerException, Processing 3.3.6 [duplicate]对象数组 NullPointerException,处理 3.3.6 [重复]
【发布时间】:2018-01-01 18:05:30
【问题描述】:

我正在尝试在 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),但我认为我太缺乏经验,无法理解我应该做什么。

请帮忙。

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

【问题讨论】:

  • TL;DR:您从未初始化数组 envArr
  • 您的编辑应该作为一个单独的问题发布,并带有一个新的minimal reproducible example

标签: java arrays object nullpointerexception processing


【解决方案1】:

您的envArr 变量是null。在使用它之前,您必须将其初始化。

你可能想要这样的东西:

BoxCl[] envArr = new BoxCl[10];

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

【讨论】:

  • 当我不知道数组的最终大小时该怎么办?因为在这种情况下,它限制了可以/必须使用的对象数量。
  • @Mr.Dude__ 不要用数组,如果你不知道它能长多长时间,就用ArrayList<BoxCl>
  • @Mr.Dude__ 你可以使用 Processing 的 append() 函数。更多信息在the reference。或者更好的是,使用ArrayListHere 是关于处理中的 ArrayLists 的教程。
  • @KevinWorkman 谢谢,现在一切正常。我使用了您的 Arraylist 教程,它运行顺利。不错的网站顺便说一句:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多