This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays

 
P Veer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.,
 
P Veer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic