卡片游戏阵列的麻烦

时间:2014-11-24 16:42:27

标签: java

基本上这个游戏要求1到52之间的整数,一旦程序运行,它将输出卡名称和套装,它适用于除52之外的每个整数,这会导致程序崩溃。有没有人有任何想法?

public static void main(String[] args) {

    int i = 0;
    int[] cards = new int[54];

    boolean notZero = true;

    while (notZero == true) {

        System.out.println("Please input a number in the range 1-52: ");

        Scanner sc = new Scanner(System.in);

        int input = sc.nextInt();

        if (input == 0) {

            break;

        } else if ((input < 1) || (input > 52)) {

            System.out.println("Invalid input please try again.");
        } else {
            cards[i] = input;
        }
        i++;

    }
    outputCards(cards, i);
}

public static void outputCards(int[] cards, int arraySize) {

    String[] suit = {"Hearts", "Diamonds", "Clubs", "Spades"};
    String[] rank = {" ", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10","Jack", "Queen", "King", 
                        "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King",
                        "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King",
                        "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    for (int j = 0; j < arraySize; j++) {

        System.out.println(rank[cards[j]] + " of " + suit[(int) (cards[j] / 13)]);

    }

}

3 个答案:

答案 0 :(得分:0)

那是因为数组的索引从0开始,所以你可能需要从0到51请求输入。另一个问题是你正在使用的print语句:

suit[(int) (cards[j] / 13)])

这意味着由于您的输入条件,您允许用户输入52,因此评估为

suit[52/13];//suit[4]

虽然你有四个元素也适合,但正如我上面所说的数组索引从0开始。所以你可以在0-3之间查询数组。所以这将导致数组索引超出绑定异常。

答案 1 :(得分:0)

第一张牌的INDEX = 0

第52张牌的指数= 51

所以你必须输入输入的数字-1

答案 2 :(得分:0)

输入无效时,不应增加索引i++;另外,您应该在while循环中检查用户输入的值不超过52个。

if (input == 0) {
    break;
} else if ((input < 1) || (input > 52)) {
    System.out.println("Invalid input please try again.");
} else {
    cards[i] = input;
    if (i++ > 51) break;
}

此外,在套装的情况下,在outputCards()方法中,当i = 52时,您可以获得超出范围的数组索引。这是因为如果用户插入52个值,则52/13 = 4,而suit[4]超出范围只有0..3项。