2

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?

1
  • +1 - Though it was a simple mistake, the question has good grammar, and is clearly written. Commented Jul 9, 2010 at 20:54

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Is your problem. Try:

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

Comments

3

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.

4 Comments

I would also like to get rid of those magic numbers (2 and 3) using private static finals.
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!
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
+1 Good point. Many beginners overlook healthy variable names.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.