可见性控制变量

时间:2016-07-04 06:29:34

标签: java

package Array;
public class ArrayLesson1
{
    static int[] array = { 10, 20, 30, 40 };
    public static void main(String[] args) {
        int i = 0;
        System.out.println("While Loop Result");
        while (i < 4) {
            int c = array[i] * array[i];
            System.out.println("Resutl = " + c);
            i++;
        }
        subclass obj = new subclass();
        obj.loopj();
        obj.loopk();
    }
}

class subclass {
    public static void loopj() {
        for (int j = 0; j < 4; j++) {
            int result = array[j] * array[j];
            System.out.println("FOR Loop J Result");
            System.out.println("Result = " + result);
        }
    }

    static void loopk() {
        for (int k = 0; k < 4; k++) {
            int result2 = array[k] + array[k];
            System.out.println("FOR Loop K Result");
            System.out.println("Result = " + result2);
        }
    }
}

从上面的代码中,我无法访问&#34;数组&#34;来自班级&#34; ArrayLesson1&#34;。

您可以在下面找到输出:

  

While循环结果

     

Resutl = 100

     

Resutl = 400

     

Resutl = 900

     

Resutl = 1600

我收到以下错误。

Exception in thread "main" java.lang.Error: Unresolved
compilation problems:   array cannot be resolved to a variable  array
cannot be resolved to a variable

at Array.subclass.loopj(ArrayLesson1.java:40)   
at Array.ArrayLesson1.main(ArrayLesson1.java:25)

1 个答案:

答案 0 :(得分:0)

您已在ArrayLesson1类中声明了数组,subclass无法看到该数组,因此您收到编译错误。

你有几个选择,

1)在subclass中创建构造函数以接受数组作为参数,并在subclass中创建一个局部变量,并将数组从ArrayLesson1传递到您的子类,如下所示:

//in subclass
private int [] array;
public subclass(int [] array) {
   this.array = array;
}

所以在你的ArrayLesson1课程中这样打电话就像这样:

subclass obj=new subclass(array); // Pass array like this

2)修改loopj()loopk()方法以接受数组作为参数,如下所示:

public static void loopj(int [] array) {
   //Codes here
//

并在ArrayLesson1中调用它:

obj.loopj(array);

3)或者如果你想使用静态引用,那么你需要在使用它之前使用classname.variablename,如下所示:

ArrayLesson1.array[j]

如果有帮助,请告诉我。

相关问题