【问题标题】:Why is this generating an Index Out of Bounds error?为什么这会产生索引越界错误?
【发布时间】:2013-06-06 15:05:27
【问题描述】:

我试图弄清楚为什么 createArithmeticSeq 中的循环超出范围,但无法弄清楚。当 i=listSize-1 时,循环应该停止,因为它是 (i=0;i

import java.util.*;

public class MagicSquare 
{
static int row, col, n, rows, columns, listSize;
static Scanner console = new Scanner (System.in);

这是发生问题的地方:

public static void createArithmeticSeq(int [] list)
    {   
    //prompt user for array size
    System.out.println("Enter size of array (in form nxn), n:");
    n = console.nextInt();
    rows = n;
    columns = n;
    listSize= (n*n);
    int first; 
    int diff;
    //prompt user for first and diff
    System.out.println("Enter first and diff : ");
    first = console.nextInt();
    diff  = console.nextInt();
    //process to create list of n*n elements 
    for (int i=0; i<listSize; i++)
    {
        list[i]=first+i*diff;
    }
}

下面是剩下的代码:

public static void matricize (int [] list, int [][] matrix)
{
    int i = 0;
//loop through each row
    for (row=0; row<matrix.length; row++)
    {
    //loop through each column
        for (col=0; col<matrix[row].length; col++)
        {
        //populate matrix with values from list
        matrix[row][col] = list[i++];
        }
     }
}
public static void printMatrix(int [][] matrix)
{

    for (row=0; row < matrix.length; row++)
    {
        for (col=0; col < matrix[row].length; col++)
            System.out.printf("%2d" + " ", matrix[row][col]);

        System.out.println("\n");
    }
}

public static void reverseDiagonal(int [] [] matrix)
{ 
    int temp;
    for (row=0; row<matrix.length / 2; row++)
    {
        temp = matrix[row][row];
        matrix[row][row] = 
            matrix[matrix.length - 1 - row] [matrix.length - 1 - row];
        matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp;
    }
    for (row=0; row<matrix.length / 2; row++)
    {
        temp = matrix[row][matrix.length - 1 - row];
        matrix[row][matrix.length - 1 - row] = 
            matrix[matrix.length - 1 - row][row];
        matrix[matrix.length - 1 - row][row] = temp;
    }
}

public static void magicCheck(int [] list, int [] [] matrix)
{
    int sum=0, sumRow=0, sumCol=0, sumDiag1=0, sumDiag2=0, magicNumber=0;

    for(int i=0; i<listSize; i++)
    {
        sum += list[i]; 
        magicNumber = sum /= 4;

    for(row=0; row<matrix.length; row++)
    {
            //sum each row, then compare to magicNumber
        for(col=0; col<matrix[row].length; col++)
        sumRow = sumRow + matrix[row][col];
        while (sumRow == magicNumber)
        {
            for(col=0; col<matrix.length; col++)
            {
                for(row=0; row<matrix[col].length; row++)
                {
                sumCol = sumCol + matrix[row][col];
                    while (sumCol == magicNumber)
                    {
                    sumDiag1 = matrix[0][0]+matrix[1][1]+matrix[2][2]+matrix[3][3];
                        while (sumDiag1 == magicNumber)
                        {
                        sumDiag2 = matrix[3][0]+matrix[2][1]+matrix[1][2]
                        +matrix[0][3];
                            while(sumDiag2 == magicNumber)
                            System.out.println("It is a magic square.");
                        }
                    }
                }
            }
        }
    }
    }
            System.out.println("It is not a magic square.");

}

public static void main (String [] args)
{
    int [] list = new int [listSize];
    createArithmeticSeq (list);
    int [] [] matrix = new int [rows] [columns];
    matricize(list, matrix);
    printMatrix(matrix);
    System.out.print("\n");
    reverseDiagonal(matrix);
    printMatrix(matrix);
    magicCheck(list, matrix);   
}

}

【问题讨论】:

    标签: java arrays loops indexoutofboundsexception


    【解决方案1】:

    在您的主目录中,您使用未初始化的“listSize”值创建列表数组,该值将为 0。 所以你应该改变你的代码,首先读取列表大小,然后创建数组:

    public static void main (String [] args)
    {
        //prompt user for array size
        System.out.println("Enter size of array (in form nxn), n:");
        n = console.nextInt();
        rows = n;
        columns = n;
        listSize= (n*n);
    
        int [] list = new int [listSize];
        createArithmeticSeq (list);
        int [] [] matrix = new int [rows] [columns];
        matricize(list, matrix);
        printMatrix(matrix);
        System.out.print("\n");
        reverseDiagonal(matrix);
        printMatrix(matrix);
        magicCheck(list, matrix);   
    }
    

    你的功能变成:

    public static void createArithmeticSeq(int [] list)
    {   
        int first; 
        int diff;
        //prompt user for first and diff
        System.out.println("Enter first and diff : ");
        first = console.nextInt();
        diff  = console.nextInt();
        //process to create list of n*n elements 
        for (int i=0; i<listSize; i++)
        {
            list[i]=first+i*diff;
        }
    }
    

    【讨论】:

    • 问过你同样的问题 ;)
    • 哈哈,这就是我删除我的原因;)
    【解决方案2】:

    当您将listsize 定义为static 时,它会得到0 的默认值。然后你打电话给createArithmeticSeq(int [] list),你基本上是在传递一个包含 0 个元素的空间的列表。如果在创建int [] list = new int [listSize]; 之后更改listsize 的值,则列表的大小不会改变。因此,您必须在知道它的大小后创建数组。

    为此,请将您的主要方法修改为

    public static void main (String [] args)
    {
        System.out.println("Enter size of array (in form nxn), n:");
        n = console.nextInt();
        rows = n;
        columns = n;
        listSize= (n*n);    
        int [] list = new int [listSize];
        createArithmeticSeq (list);
        int [] [] matrix = new int [rows] [columns];
        matricize(list, matrix);
        printMatrix(matrix);
        System.out.print("\n");
        reverseDiagonal(matrix);
        printMatrix(matrix);
        magicCheck(list, matrix);   
    }
    

    和你的 createArithmeticSeq 方法一样

    public static void createArithmeticSeq(int [] list)
    {   
        int first; 
        int diff;
        //prompt user for first and diff
        System.out.println("Enter first and diff : ");
        first = console.nextInt();
        diff  = console.nextInt();
        //process to create list of n*n elements 
        for (int i=0; i<listSize; i++)
        {
            list[i]=first+i*diff;
        }
    }
    

    【讨论】:

    • 你在电脑上安装了键盘记录器吗? ;) 多么同步!
    • @Pragmateek 我逐点回答,首先是理论,然后是代码。
    • 同样的方式:首先忍者急于回答简短的答案,然后充实到完美:)你当然得到了我的 +1
    • 太棒了!太感谢了。这很有道理,我只是忽略了它。
    【解决方案3】:

    当您在main 中创建列表数组时,您使用的是listSize。由于你没有初始化它,它的值为0。

    createArithmeticSeq 方法中,您将其大小更改为n*n,但这不会影响数组的大小,仍然为0。

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 2020-07-26
      • 2018-04-02
      • 2021-10-11
      相关资源
      最近更新 更多