首页 > 解决方案 > 如何通过调用另一个类中对象的方法来打印while循环

问题描述

运行应用程序时出现此错误:

线程“主”java.lang.IllegalAccessError 中的异常:WhileLoop 类试图访问字段 LoopClass.x(WhileLoop 位于加载程序 com.sun.tools.javac.launcher.Main$MemoryClassLoader @782663d3 的未命名模块中;LoopClass 位于未命名模块中WhileLoop.main(WhileLoop.java:11) 处的加载程序“应用程序”)

public class WhileLoop {
    LoopClass loopObj; //bring loopObj as new attribute for the WhileLoop class of type 'CodePractice'

    public WhileLoop() {    //constructor
    }

    public static void main(String[] args) {

        LoopClass loopObj = new LoopClass();
        loopObj.whileLoop(loopObj);
        System.out.println(loopObj.x);
    }

}

public class LoopClass {
int x;
    public LoopClass() {
        int x = 1;
    }

    public static void main(String[] args) {
    }

    public void whileLoop(LoopClass loopObj) {   //pass loopObj as a parameter of whileLoop
        loopObj.x = 1;
        while (loopObj.x < 5) {
            loopObj.x++;
        }

    }
}

我想通过调用对象上的方法来打印 while 循环的内容。我该怎么做?

标签: illegalaccessexception

解决方案


可以通过将 whileLoop 声明为staticint x作为 LoopClass 的参数传递,为其分配值“this.x”,最后调用对象“loopObj”的方法来规避该错误。谢谢萨钦·桑尼。


推荐阅读