Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

scope error in if statement in java program

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Others have answered why it's a problem and how to avoid it, but I'd actually change the approach anyway. Currently you have two blocks with repeated code - why not avoid that?

int length = Math.min(N, 26);
MyStruct array[] = new MyStruct[length];
for(int i = 0; i < array.length; i++) {
    array[i] = new MyStruct();
}

MyClass myClass = new MyClass();
myClass.myMethod(array);

(Note that the name MyStruct has connotations which may well not be appropriate in Java. I realize it's just a dummy name, but Java doesn't have anything like a "struct" from C or C#. Just in case you're expecting something else...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...