File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arrays" Watch "Arrays" New topic


P Veer

Joined: Oct 21, 2003
Posts: 9
Iam creating an array in a class which has no main method like this:
int[][] Allocation = new int[n][3];
Then Iam trying to initialise all the elements to 1 in the constructor:
n is passed in through the constructor(parameter)
for (int row=0; row <= n-1; row++) {
for (int col=0; col <=2; col++) {
Allocation[row][col] = 1; } }
It gives me an error:
java.lang.ArrayIndexOutOfBoundsException: 0

Please Help me out!!!

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

My guess (there are other possibilities, but this one is likely) is that you've got something like this:

Here the array will be constructed when "n" is still 0, because instance initializers run before the constructor body.
To fix this, move the array construction inside the constructor -- i.e.,

[Jess in Action][AskingGoodQuestions]
P Veer

Joined: Oct 21, 2003
Posts: 9
Thanks a lot!!! It Works
Iam working on a program that uses many arrays like that.And ive been creating the whole array inside.Using the new keyword inside the constructor was the problem I wasnt able to detect.
I really appreciate it and Thanks once again!!!
I agree. Here's the link:
subject: Arrays
It's not a secret anymore!