【发布时间】:2012-03-27 20:32:42
【问题描述】:
我在 if 语句中遇到了范围问题,至少,我很确定这是我的错误所在,而且我不确定如何解决这个问题(我在编程)。
基本上,如果我在 if 语句中声明某些内容,则该变量(在本例中为结构数组)似乎不存在于 if 语句之外。但是,我确实需要将数组的声明放在 if/else 中,因为数组的大小取决于 N,那么我该如何解决这个错误呢?
该程序是用 Java 编写的,我使用的是 Eclipse。非常感谢任何见解。
//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
【问题讨论】:
标签: java if-statement scope