[英]Java out of bounds exception inside nested for loop
这可能很容易,但是我遇到了一个异常,而且我不确定如何解决它。
基本上,我试图创建一个整数字段的“表”,以便我可以使用它们来查找整数字段中的所有值是否都创建了一个幻方。 嵌套的for循环最多可以创建一个8x8的正方形,它将创建正方形的第一行,但是却给了我一个超出范围的错误。
错误发生在嵌套的for循环内部,其中我将IntegerField添加到GUI。
如果有人可以帮助,那就太好了。 让我知道您是否需要更多详细信息。
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)
{
}
}
}
i <= size
for循环条件应该始终引发红色标记,因为如果i == size,则超出了数组或集合的大小。 请注意,数组和集合基于0,从0到size-1。
相反,它几乎应该总是i < size
您的所有循环都迭代到最大大小,这将导致ArrayIndexOutOfBoundException。 数组索引从0
到size-1
。 这是代码中的此类循环之一:
for (int i = 0; i <= size; i++)
您只需要迭代循环直到大小
for (int i = 0; i < size; i++)
相应地纠正其他循环
size
从未初始化。 并且您的<=
应该是for循环中的<
。
实际上,如果您使用size
作为常量来设置数组的大小,则应使用i < size - 1
in for
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.