簡體   English   中英

嵌套for循環內的Java越界異常

[英]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。 數組索引從0size-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM