尝试合并数组列表时不断收到 IndexOutOfBounds 异常

时间:2021-02-16 02:39:35

标签: java indexoutofboundsexception

我正在做一个学校作业(所以仍然是一个菜鸟)但似乎无法弄清楚为什么我不断收到 IndexOutOfBoundsException。任何帮助都是赞赏。这很可能是一些愚蠢的错误,但我非常擅长不注意这些错误。它应该将切片对象分成 3 个 ArrayList,打乱这些列表,然后根据颜色将它们按正确的顺序放回。

public void scramble()
{
    ArrayList<Slice> temp = new ArrayList<>();
    ArrayList<Slice> red = new ArrayList<>();
    ArrayList<Slice> black = new ArrayList<>();
    ArrayList<Slice> blue = new ArrayList<>();
    int blackListCount = 0;
    int redListCount = 0;
    int blueListCount = 0;
    for (Slice s : slices) {
        if (s.getColor().equals("red")) {
            red.add(s);
        } else if (s.getColor().equals("black")) {
            black.add(s);
        } else if (s.getColor().equals("blue")) {
            blue.add(s);
        }
    }
    blueScram(blue);
    blackScram(black);
    redScram(red);
    for (int i = 0; i < slices.size() - 1; i++) {
        if (i % 5 == 0) {
            temp.add(i, black.get(blackListCount));
            blackListCount++;
        }
        if (i % 2 == 0) {
            temp.add(i, blue.get(blueListCount));
            blueListCount++;
        }
        if (i % 2 == 1) {
            temp.add(i, red.get(redListCount));
            redListCount++;
        }

    }
    slices.clear();
    slices = temp;
}

private void blueScram(ArrayList<Slice> blue) {
    for (int i = 0; i < blue.size(); i++) {
        switchSlice(blue, i, (int) (Math.random() * (blue.size())));
    }
}
private void redScram(ArrayList<Slice> red) {
    for (int i = 0; i < red.size(); i++) {
        switchSlice(red, i, (int) (Math.random() * (red.size())));
    }
}
private void blackScram(ArrayList<Slice> black) {
    for (int i = 0; i < black.size(); i++) {
        switchSlice(black, i, (int) (Math.random() * (black.size())));
    }
}

private void switchSlice(ArrayList<Slice> list, int firstIndex, int lastIndex) {
    try {
        Slice temp = list.get(firstIndex);
        list.set(firstIndex, list.get(lastIndex));
        list.set(lastIndex, temp);
    } catch (IndexOutOfBoundsException e) {
        System.out.println("IndexOutBounds while trying to randomize/switch elements of a slice list");
        e.printStackTrace();
    }
}

这是初始(给定)切片创建/排序代码

private static int[] getStandardPrizes()
{
    int[] arr = new int[20];
    for (int i=0; i < 20; i++)
    {
        if (i%5 == 0)
            arr[i] = i*1000;
        else if (i%2 == 1)
            arr[i] = i*100;
        else
            arr[i] = i*200;
    }
    return arr;
}

我在 if(i % 5 == 0) 和周围 for 循环范围内的其他 if 语句处出错

0 个答案:

没有答案
相关问题