0

这可能很容易,但我遇到了一个越​​界异常,我不知道如何解决它。

基本上,我正在尝试创建一个整数字段的“表”,以便我可以使用它们来查找整数字段中的所有值是否都创​​建了一个幻方。嵌套的 for 循环应该创建一个 8x8 的正方形,它会创建正方形的第一行,但是它给了我一个超出范围的错误。

错误发生在我将 IntegerField 添加到 GUI 的嵌套 for 循环内。

如果有人可以提供帮助,那就太好了。如果您需要更多详细信息,请告诉我。

import javax.swing.*;
import BreezySwing.*;

public class Interface extends GBFrame{ 
    //Create integerField array to create input for magic square
    public IntegerField[][] magicSquare;
    //Create input button, integer field which sets size of square
    public IntegerField squareSize;
    public JButton inputSize;
    //Create check square button
    public JButton checkSquare;
    //Label to output if there is a magic square
    public JLabel squareLabel;
    //Size of square variable
    public int size;

    //CalcSquare object
    CalcSquare calc = new CalcSquare();

    //Constructor for Square interface
    public Interface()
    {
        squareSize = addIntegerField (0, 1, 1, 1, 1);
        inputSize = addButton ("Input Size", 2, 1, 1, 1);
        squareLabel = addLabel ("", 3, 1, 1, 1);
        checkSquare = addButton ("Check Square", 4, 1, 1, 1);
    }   
    //Creates IntegerFields on the GUI as needed.
    public void createFields()
    {
        for (int i = 0; i <= size; i++)
        {
            for (int x = 0; x <= size; x++)
            {
                magicSquare = new IntegerField[i][x];
    }
        }
    }

public void buttonClicked(JButton buttonObj)
{
        if (buttonObj == inputSize)
        {
            size = squareSize.getNumber();
            createFields();
            for (int i = 0; i <= size; i++)
            {
                for (int x = 0; x <= size; x++)
                {
                    magicSquare[i][x] = addIntegerField (0, i+1, x+1, 1, 1);
                }
            }   
        }
        else if (buttonObj == checkSquare)
        {       
        }
    }
}
4

3 回答 3

2

一个 for 循环条件i <= size应该总是引发危险信号,因为如果 i == size,你已经超出了数组或集合的大小。请注意,数组和集合是基于 0 的,并且从 0 变为 size - 1。

相反,它应该几乎总是i < size

于 2013-10-01T00:51:24.237 回答
0

您所有的循环都在迭代到大小,这将导致 ArrayIndexOutOfBoundException。数组索引从0到开始size-1。这是您的代码中的此类循环之一:

for (int i = 0; i <= size; i++)

你只需要迭代循环直到大小

for (int i = 0; i < size; i++)

相应地更正其他循环

于 2013-10-01T00:52:16.100 回答
0

size永远不会被初始化。你<=应该<在 for 循环中。

事实上,如果你使用size常量来设置数组的大小,你应该i < size - 1for循环中使用。

于 2013-10-01T00:53:07.870 回答