tags:

views:

77

answers:

3

First of all, Beginner here.

I'm using this code.

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]);
            }
        }
    }
}

It compiles perfectly, but when running it, after displaying 3 numbers correctly I'm getting the following error.

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

Where am I going wrong?

+7  A: 

You are incrementing j while checking against i.

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

j will keep incrementing which will eventually give you an IndexOutOfBoundsException

Andres
Cannot believe I mistyped it. This is one bad question.
MoonStruckHorrors
+2  A: 
for(int j=0; i<=2; j++) {

Is your problem. Try:

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

I would write it like this:

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]);
            }
        }
    }
}

The major difference is that I use the .length member rather than hard coded values. That way if I change it to x = new int[3][2]; then the code magically works and stays within its bounds.

The other big difference is that I use row/col instead of i/j. i/j are fine (and traditional) but I find when dealing with arrays of arrays (Java doesn't actually have multi-dimensional arrays) that it is easier to keep track of things if I use the more meaningful row/col (helps prevent you from doing things like for(int col = 0; row < x.length; col++)... which, incidentally, is the bug you have.

TofuBeer
I would also like to get rid of those magic numbers (2 and 3) using private static finals.
Joni
yeah, I was going to do that too, but didn't want to make it soooo different - but given you feel that way too I'll do it!
TofuBeer
Did not you mean x.length ?Currently at row:for(int row = 0; row < row.length; row++) you get error:The primitive type int of row does not have a field length MDArrays.java /StackOverflow/src line 24 Java Problem
Miro A.
yup... thx (I didn't compile it...)
TofuBeer
+1 Good point. Many beginners overlook healthy variable names.
Andres