如何修复数组列表内的IndexOutOfBoundException()?

时间:2018-12-27 22:54:52

标签: java arraylist indexoutofboundsexception

在我的程序中,我使用分层数组列表来记住有关按钮的属性(按某些按钮是“正确的”,而其他按钮则是“错误的”),其中外层取决于在其上找到按钮的JPanel以及内层是布尔变量,为true或false。但是按钮的数量是随机的。 while (buttonInfo.get(buttonInfo.size() - 1).get(rightButton) == true) {行有一个IndexOutOfBoundsException,所以我一直被困在那行,但是我怀疑buttonInfo.get(buttonInfo.size() - 1).add(rightButton, true);处也有同样的问题。

    int numberOfButtons = rnd.nextInt(5) + 2;
    buttonInfo.add(new ArrayList<Boolean>());
    JPanel newPanel = new JPanel();
    newPanel.setLayout(new GridLayout(2, 1, 5, 0));
    JLabel panelMessage = new JLabel("Choose one.");
    newPanel.add(panelMessage);
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1, 0, 0, 5));
    for (int b = 0; b < numberOfButtons; b++) {
        JButton newButton = new JButton(String.valueOf(b));
        newButton.addActionListener(this);
        buttonPanel.add(newButton);
    }
    for (int a = 0; a < (numberOfButtons/2); a++) {
        int rightButton = rnd.nextInt(numberOfButtons);
        while (buttonInfo.get(buttonInfo.size() - 1).get(rightButton) == true) {
            rightButton = rnd.nextInt(numberOfButtons);
        }
        buttonInfo.get(buttonInfo.size() - 1).add(rightButton, true);
    }

如何修正while语句,使其在范围之内?

1 个答案:

答案 0 :(得分:0)

此行:

buttonInfo.add(new ArrayList<Boolean>());

您仅将一项添加到列表buttonInfo
此项是已初始化但的列表。
不会填充此列表(至少在您提供的代码中)。
所以这个:

buttonInfo.get(buttonInfo.size() - 1).get(rightButton)

等效于:

buttonInfo.get(0).get(rightButton)

无论rightButton的值是什么,都会引发错误,
因为buttonInfo.get(0)