Array Index Out of Bounds error on Array List

You are making it sooo complicated :smile:

Here something that is working with explanations. Hope it helps:

StringList originalFruits; // Will always contain the list of all the fruits
StringList fruits; // Will be the array that we use to get a new random fruit

void setup(){
  // Initializing both list
  originalFruits = new StringList("apple","orange","grape","banana","lemon");
  fruits = originalFruits.copy(); //It works because we are using string, It would't with custom classes
}


void randomSelect(){
  int idx = (int)random(fruits.size()); // Get a random index from 0 to the size of the array
  println(fruits.get(idx)); // Write in the console the name of the random picked fruit
  fruits.remove(idx); // Remove that fruit from the list since we dan't want to pick it again
}


void mouseClicked(){
  if(fruits.size() > 0) { // While there is still some fruit to pick we want to pick one
    randomSelect(); // So we pick one
  } else { // On the other case it means that we picked everything
    println("GAME OVER"); // So we are game over
    fruits = originalFruits.copy(); // And we need to fill the list of fruit again
  }
}


void draw(){ 
  
}
1 Like