• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializing Arrays

 
Mitch Krah
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code:

package module6;

class ErrorInfo {
String msgs[] = {
"Output Error",
"Input Error",
"Disk Error",
"Index Out-Of-Bounds"
};

int howBad[] = new int[3];

for(int i = 0; i < howBad.length; i++)
howBad[i] = i * 2;

Err getErrorInfo(int i) {
if(i >= 0 & i < msgs.length)
return new Err(msgs[i], howBad[i]);
else
return new Err("Invalid Error Code", 0);
}
}

However, the compiler will not recognize the "for" loop that I have used to intialize my "howBad" array. I get "illegal start of type" error. Can someone shed some light on this error? I do not get it? The "for" loop is pretty fundamental and I have been using it for months. Is there some requirement that it has to be inside a methog or something? Your assistance is appreciated.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to put that for loop inside an initializer block like this:


Executable code must be inside a method, a constructor, or an initializer.
[ December 04, 2004: Message edited by: Mike Gershman ]
 
Raj Chila
Ranch Hand
Posts: 128
Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
note that your for loop must be with in some method block. you can only "declare" some memebers and initializers at class level.
 
Mitch Krah
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK. So help me out here?

In order to initialize an array (other than declaring values), I need to create a method, which I can then use a "for" loop to intialize. Then to get access to the array outside the class, I need to instantiate an object of the class, call the method (using the dot operator). And, then to get a specific value of the array I need to call the array with a specific index #. Because, the array values are only valid withing the method.

So to get a specific value of the Array:

ArrayClass ob = new ArrayClass();
int = ob.arrayMethod(array[2]);

Is this correct?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need a method, just an initializer block.

It will be executed before the constructors.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic