Home > Back-end >  Processing - Array index out of bounds error
Processing - Array index out of bounds error

Time:12-21

I'm trying to use an array of objects to have barrels fall from the top of the screen to the bottom. (Like that old donkey kong game.) However, I can't seem to find a way to create more instances of the object than whatever the initial length of the array was. Anyone know a way to do this?

Here's the code:

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

CodePudding user response:

Use an ArrayList instead of a native array. ArrayList will expand capacity as needed, whereas an array is fixed size and cannot be changed (you'd need to create a new larger array each time, which under the covers is what an ArrayList handles for you).

CodePudding user response:

You can use ArrayList for this. You will change

// 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

I highly recommend this for getting started with lists https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

Happy learning :)

  • Related