【问题标题】:Processing - Array index out of bounds error处理 - 数组索引超出范围错误
【发布时间】:2022-01-22 05:42:59
【问题描述】:

我正在尝试使用一组对象让桶从屏幕顶部落到底部。 (就像那个古老的大金刚游戏一样。)但是,我似乎找不到一种方法来创建比数组的初始长度更多的对象实例。有人知道这样做的方法吗?

代码如下:

Man Man;
Man background;
Man ladders;
PFont font1;
int time;
boolean run;
boolean newBarrel;
int barrelTotal;
Barrel[] barrel = new Barrel[100];
void setup() {
  newBarrel = false;
  run = true;
  barrelTotal = 1;
  time = millis();
  size(800, 800);
  Man = new Man();
  background = new Man();
  ladders = new Man();
  for (int i = 0; i < barrel.length; i++) {
    barrel[i] = new Barrel();
  }
}
void draw() {
  if (run == true) {
    for (int i = 0; i < barrel.length; i++) {
      if ((Man.bottom-10 >= barrel[i].top)&&(Man.bottom-10 <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
        print("GAME OVER!");
        run = false;
      }
      if ((Man.top >= barrel[i].top)&&(Man.top <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
        print("GAME OVER!");
        run = false;
      }
    }
  }
  if (run == true) {
    background.createBackground();
    Man.ladders();
    Man.movement();
    Man.createMan();
    //spawns a barrel every second
    if (millis()> time + 10) {
      newBarrel = false;
      print("     " + barrelTotal + "        ");
      time = time + 10;
      barrelTotal = barrelTotal+1;
      newBarrel = true;
    }
    for (int i = 0; i < barrelTotal; i++) {
      if (newBarrel == true) {
      }
      barrel[i].gravity();
      barrel[i].createBarrel();
    }
    //if(barrelTotal == 100){
    //for (int i = 0; i < 50; i++){
    // barrel[i] = "???";
    //}
    //}
  }
}

【问题讨论】:

    标签: java arrays object processing instantiation


    【解决方案1】:

    使用 ArrayList 而不是原生数组。 ArrayList 将根据需要扩展容量,而数组是固定大小且无法更改的(您每次都需要创建一个新的更大的数组,在幕后是 ArrayList 为您处理的)。

    【讨论】:

      【解决方案2】:

      您可以为此使用ArrayList。你会改变

      // from
      Barrel[] barrel = new Barrel[100]; // i suggest naming it to barrels instead of barrel
      // to 
      ArrayList<Barrel> barrel = new ArrayList<>(); 
      // or better 
      List<Barrel> barrel = new ArrayList<>();
      // from 
       for (int i = 0; i < barrel.length; i++) {
          barrel[i] = new Barrel();
        }
      // to
       for (int i = 0; i < barrel.length; i++) {
          barrel.add(new Barrel());
        }
      // from
      barrel[i].<some-method()/attribute>
      // to
      barrel.get(i).<some-method()/attribute>
      // etc
      

      我强烈推荐这个开始使用列表 https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-02
        • 1970-01-01
        • 1970-01-01
        • 2012-06-04
        相关资源
        最近更新 更多