嵌套for循环内的Java越界异常
这可能是一个简单的问题,但我得到了一个越界异常,我不知道如何修复它 基本上,我正在尝试创建一个整型字段的“表”,这样我就可以使用它们来查找整型字段中的所有值是否都创建了一个幻方。嵌套for循环最多应创建一个8x8正方形,它将创建正方形的第一行,但它会给我一个越界错误 该错误发生在嵌套for循环中,我正在将IntegerField添加到GUI中 如果有人能帮忙,那就太好了。如果你需要更多的细节,请告诉我嵌套for循环内的Java越界异常,java,magic-square,Java,Magic Square,这可能是一个简单的问题,但我得到了一个越界异常,我不知道如何修复它 基本上,我正在尝试创建一个整型字段的“表”,这样我就可以使用它们来查找整型字段中的所有值是否都创建了一个幻方。嵌套for循环最多应创建一个8x8正方形,它将创建正方形的第一行,但它会给我一个越界错误 该错误发生在嵌套for循环中,我正在将IntegerField添加到GUI中 如果有人能帮忙,那就太好了。如果你需要更多的细节,请告诉我 import javax.swing.*; import BreezySwing.*; pu
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)
{
}
}
}
import javax.swing.*;
进口风机。*;
公共类接口扩展了GBFrame{
//创建integerField数组以创建幻方的输入
公共整型字段[][]magicSquare;
//创建输入按钮,设置正方形大小的整数字段
公共整数域的平方大小;
公共JButton输入大小;
//创建复选框按钮
公共JButton checkSquare;
//如果存在幻方,则输出标签
公共标签;
//平方变量的大小
公共整数大小;
//CalcSquare对象
CalcSquare calc=新的CalcSquare();
//方形接口的构造函数
公共接口()
{
squareSize=addIntegerField(0,1,1,1);
inputSize=addButton(“输入大小”,2,1,1,1);
squareLabel=addLabel(“,3,1,1,1);
checkSquare=addButton(“checkSquare”,4,1,1,1);
}
//根据需要在GUI上创建整数字段。
public void createFields()
{
for(int i=0;iA for循环条件为i您的所有循环都迭代到最大大小,这将导致ArrayIndexOutOfBoundException。数组索引从0
到size-1
。代码中有一个这样的循环:
for (int i = 0; i <= size; i++)
for(int i=0;isize
从未初始化。而您的边界外异常的奇怪之处是什么
?数组有基于0的索引。为什么要在循环中执行此操作magicSquare=new IntegerField[i][x];
?
for (int i = 0; i < size; i++)