gpt4 book ai didi

Java嵌套for循环中的越界异常

转载 作者:行者123 更新时间:2023-12-02 06:41:19 24 4
gpt4 key购买 nike

这可能很简单,但我遇到了越界异常,并且我不知道如何修复它。

基本上,我试图创建一个整数字段“表”,以便我可以使用它们来查找整数字段中的所有值是否创建一个幻方。嵌套的 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)
{
}
}
}

最佳答案

for循环条件i <= size应该始终发出危险信号,因为如果 i == size,则说明您已经超出了数组或集合的大小。请注意,数组和集合是从 0 开始的,并且大小从 0 到 - 1。

它应该几乎总是 i < size

关于Java嵌套for循环中的越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com