aspose file tools*
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arrays" Watch "Arrays" New topic
Author

Arrays

P Veer
Greenhorn

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!!!


maverickthinker
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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
Greenhorn

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: http://aspose.com/file-tools
 
subject: Arrays