簡體   English   中英

處理 - 數組索引超出范圍錯誤

[英]Processing - Array index out of bounds error

我正在嘗試使用一系列對象讓桶從屏幕頂部落到底部。 (就像那個舊的大金剛游戲一樣。)但是,我似乎找不到一種方法來創建比數組的初始長度更多的 object 實例。 有人知道這樣做的方法嗎?

這是代碼:

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] = "???";
    //}
    //}
  }
}

使用 ArrayList 而不是本機陣列。 ArrayList 將根據需要擴展容量,而陣列是固定大小且無法更改(您每次都需要創建一個更大的新陣列,在幕后是 ArrayList 為您處理的)。

您可以為此使用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

快樂學習:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM