I'm having an issue with scope in an if statement, at least, I'm pretty sure that is where my error is, and I'm not sure of how to fix the issue (I'm pretty new at programming).
Basically, it seems that if I declare something within an if statement, the variable (in this case, an array of structs) does not exist outside of the if statement. However, I really need the declaration for the array to be inside of an if/else because the size of the array is dependent upon N, so how can I fix this error?
The program is in Java, and I'm using Eclipse. Any insight is greatly appreciated.
//declare an int (used in determining array length)
int N = 4;
//declare instance of MyClass
MyClass myClass = new MyClass();
//declare and array, then initialize each struct in that array
if(N <= 26){
MyStruct array[] = new MyStruct[260];
for(int i = 0; i < array.length; i++){
array[i] = new MyStruct();
}
}
else{
MyStruct array[] = new MyStruct[N*10];
for(int i = 0; i < array.length; i++){
array[i] = new MyStruct();
}
//lots of other code goes here of stuff that needs to be done before myMethod can be called
//call a method in myClass that requires 'array' to be passed in
myClass.myMethod(array); // ERROR - ARRAY CANNOT BE RESOLVED TO BE A VARIABLE
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…