帮助二维数组

时间:2010-07-08 16:16:05

标签: java arrays

首先,初学者在这里。

我正在使用此代码。

class MDArrays {
    public static void main(String[] args) {
        int[][] x;
        int t=2;
        x = new int[2][3];

        for(int i=0; i<=1; i++) {
            for(int j=0; i<=2; j++) {
                x[i][j] = t;
                t += 2;
                System.out.println(x[i][j]);
            }
        }
    }
}

它编译完美,但在运行时,正确显示3个数字后,我收到以下错误。

Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)

我哪里错了?

3 个答案:

答案 0 :(得分:8)

在检查i时,您正在递增j。

for(int j=0; i<=2; j++)

j将继续递增,最终会给你一个IndexOutOfBoundsException

答案 1 :(得分:3)

for(int j=0; i<=2; j++) {

你的问题。尝试:

for(int j=0; j<=2; j++) {

答案 2 :(得分:3)

我会这样写:

class MDArrays
{
    private static final int ROWS;
    private static final int COLS;
    private static final int START_VALUE;
    private static final int INC_VALUE;

    static
    {
        ROWS        = 2;
        COLS        = 3;
        START_VALUE = 2;
        INC_VALUE   = 2;
    }

    public static void main(String[] args) 
    {
        final int[][] x;
        int           t;

        x = new int[ROWS][COLS];
        t = START_VALUE;

        for(int row = 0; row < x.length; row++) 
        {
            for(int col = 0; col < x[row].length; col++) 
            {
                x[row][col] = t;
                t += INC_VALUE;
                System.out.println(x[row][col]);
            }
        }
    }
}

主要区别在于我使用.length成员而不是硬编码值。这样,如果我将其更改为x = new int[3][2];,那么代码会神奇地工作并保持在其范围内。

另一个很大的区别是我使用row / col而不是i / j。 i / j很好(和传统的),但我发现在处理数组数组(Java实际上没有多维数组)时,如果我使用更有意义的行/ col,则更容易跟踪事物(帮助阻止你做for(int col = 0; row < x.length; col++)这样的事情......顺便提一下,这就是你的错误。

相关问题