| Author |
Initializing Arrays
|
Mitch Krah
Ranch Hand
Joined: Sep 06, 2004
Posts: 41
|
|
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
Joined: Mar 13, 2004
Posts: 1272
|
|
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 ]
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
Raj Chila
Ranch Hand
Joined: Mar 18, 2004
Posts: 125
|
|
|
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
Joined: Sep 06, 2004
Posts: 41
|
|
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
Joined: Mar 13, 2004
Posts: 1272
|
|
You don't need a method, just an initializer block. It will be executed before the constructors.
|
 |
 |
|
|
subject: Initializing Arrays
|
|
|