0

I am trying to write a guessing game where we are not allowed to use the same card twice and we need to use an array of 15 card (objects) I have created everything (probably not in an ideal fashion) but I keep getting the error java.land.ArrayIndexOutOfBoundException: Index 15 is out of bounds for length 15 when I try to answer all questions correctly it won't complete the deck of cards. I don't understand why. Here is the relevant code:

while (CountryCard.instances < 30) {
    System.out.println("Would you like to guess the capital of a country?"
            + " Hit 1 for yes, or 2 for no (Case sensitive)");
    yesNo = input.nextInt();
    if (yesNo == 2) {
        return;
    }
    int randomNumber = 0 + (int) (Math.random() * ((game.length)+1 ));
    while(game[randomNumber].used==true){
        randomNumber = 0 + (int) (Math.random() * ((game.length)+1 ));
    }
    System.out.println("What is the Capital of "
            + game[randomNumber].getName() + "?");
    game[randomNumber].usedCard(1);
    guess = input.next();
    if (guess.equals(game[randomNumber].getCapital())) {
        System.out.println("Correct! :)");
    } else {
        System.out.println("Incorrect! :(");
    }
}//end of while
System.out.println("Thanks for playing :)");
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

0

Array indices are 0 based that means the 15th element has an index of 14

Reinhold
  • 546
  • 1
  • 3
  • 14
0

The index for any Array/List starts with 0, so a object with length of 9, will have the max object index of 8

char[] a = "Apple".toCharArray();

so the length of a is 5, but a[4] = 'e'

mTvare
  • 327
  • 1
  • 2
  • 14