首页 > 解决方案 > 我不断收到错误“索引 5 超出长度 5 的范围”但不知道要更改什么

问题描述

我对编码很陌生,所以请多多包涵,我只是在尝试洗牌数组的方法,以便最终在我用 Java 创建的纸牌游戏中洗牌。我知道索引 5 超出了长度 5 的范围,但令我困惑的是错误不会总是弹出。有时我尝试运行我的代码并且它工作得很好,有时我得到错误,即使我在运行它的时间之间没有更改任何内容。

public class Card{

    public static void shuffle(Object[] array) {

        int noOfCards = array.length;

        for (int i = 0; i < noOfCards; i++) {

            int s = i + (int)(Math.random() * (noOfCards - 1));

            Object temp = array[s]; //this is the first line it says has a problem
            array[s] = array[i];
            array[i] = temp;
        }
    }

    public static void main(String[] args) {

        String[] strOfCards = {"A","B","C","D","E"};

        Card.shuffle(strOfCards); //this is the second line that has a problem
        for(int i = 0; i < strOfCards.length; i++) {
            System.out.println(strOfCards[i] + " ");
        }
    }
}

我不知道如何更改有缺陷的线条,欢迎提出任何建议!*** 我尝试更改字符串中的字母数,但随后错误随之更改,即“索引 6 超出长度 6 的范围”

标签: javaarraysexception

解决方案


考虑以下几行:

for (int i = 0; i < noOfCards; i++) {
    int s = i + (int)(Math.random() * (noOfCards - 1));
    Object temp = array[s]; //this is the first line it says has a problem

i 从 0 变化到 noOfCards - 1 你的随机数表达式从 0 变化到 noOfCards - 2 所以 s 从 0 变化到 (2 * noOfCards) - 3

然后array[s]将在 s >= noOfCards 时抛出异常

每次运行它都不会发生,因为有时随机数都恰好在 noOfCards 之下

如果您想与随机的其他卡交换,那么您可以尝试:

Random random = new Random();
int s = (i + random.nextInt(noOfCards - 1)) % noOfCards;

我知道您将此作为学习机会,但如果您不知道,有一种Collections.shuffle方法可用于ArrayList在一个命令中对集合进行混洗。


推荐阅读