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
解决方案
You need to move the array declaration MyStruct array[]; outside of the if block. You answered your own question, in fact, when you declare a local variable inside a block (a piece of code surrounded by {}), the variable will only be visible inside that block, as per the scoping rules of the Java language.
What you can do inside the if or else blocks, is instantiating the array to the correct size, like this:
MyStruct[] array;
if (N <= 26) {
array = new MyStruct[260];
for (int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}
}
else {
array = new MyStruct[N*10];
for (int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}
}
An even shorter solution would be:
MyStruct[] array = new MyStruct[N <= 26 ? 260 : N*10];
for (int i = 0; i < array.length; i++) {
array[i] = new MyStruct();
}