索引超出界限异常

nhaq1z21  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(319)

这个问题在这里已经有答案了

是什么导致java.lang.arrayindexoutofboundsexception以及如何防止它(26个答案)
上个月关门了。
我试图写一个猜测游戏,我们不允许使用同一张牌两次,我们需要使用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 :)");
1wnzp6jl

1wnzp6jl1#

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

t8e9dugd

t8e9dugd2#

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

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

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

相关问题