索引是越界异常



我正试图写一个猜谜游戏,不允许我们使用同一张牌两次,我们需要使用一个由15张牌(对象(组成的数组。我已经创建了所有东西(可能不是以理想的方式(,但我一直收到错误java.land.ArrayIndexOutOfBoundException:当我试图正确回答所有问题时,索引15超出了长度15的界限一副牌。我不明白为什么。以下是相关代码:

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 :)");

数组索引基于0,这意味着第15个元素的索引为14

任何数组/列表的索引都以0开头,因此长度为9的对象的最大对象索引为8

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

所以a的长度是5,但是a[4]='e'

最新更新