【问题标题】:Java class[i].subclass exception cannot read feild "subclass" because class[i] is null [duplicate]Java class[i].subclass 异常无法读取 feild \"subclass\" 因为 class[i] 为空 [重复]
【发布时间】:2022-11-12 19:26:17
【问题描述】:

感谢您的关注。让我们直奔问题。

所以这就是我的课程的样子

`

class Moon{
        double distance;
        double angle;
        double diameter;
        String col;
        double centreOfRotationDistance;
        double centreOfRotationAngle;
    }
class Planet{
        double distance;
        double angle;
        double diameter;
        String col;
        Moon moon = new Moon();
    }

`

但是,当我尝试像这样访问Planet[i].moon 时,java 会抛出NullPointerException。 我的代码有什么问题吗?如果是,我该如何解决?

`

System.out.println("Creating planets...");
        String[] colArray = {"red", "orange", "yellow", "green", "blue", "indigo", "violet", "white", "red"};
        for(int i = 0; i < 8; i++){
            planets[i] = new Planet();
            planets[i].distance = 100 + (i * 100);
            planets[i].angle = 0 + (i * 20);
            planets[i].diameter = 20 + (i * 10);
            planets[i].col = colArray[i];
            System.out.println("Planet " + i + " created");
            System.out.println("Creating moon..." + i);
            planets[i].moon.distance = 10 + (i * 5);
            planets[i].moon.angle = 0 + (i * 20);
            planets[i].moon.diameter = i + 2;
            planets[i].moon.col = colArray[i++];
            planets[i].moon.centreOfRotationDistance = (100 + (i * 100))/10;
            planets[i].moon.centreOfRotationAngle = 0 - (i * 20);
        }
        System.out.println("Done creating planets.");
        System.out.println("Creating the sun...");

`

堆栈,以防它有用

再次感谢阅读/回答

我的原始代码是 this

我认为我可能过于雄心勃勃,无法访问我正在创建并从中获取价值的课程。 因此我尝试将代码更改为上面的sn-p,但是它不起作用?

问了几个朋友,没有人知道为什么会出错。因此发布

【问题讨论】:

    标签: java oop exception nullpointerexception


    【解决方案1】:

    这些行是问题所在:

    planets[i].moon.col = colArray[i++];
    planets[i].moon.centreOfRotationDistance = (100 + (i * 100))/10;
    

    在这些行的第一行中,您将增加 i - 这意味着下一个行,planets[i] 指的是元素仍然为空的数组索引。

    我怀疑只是这个简单的更改就可以解决问题:

    planets[i].moon.col = colArray[i];
    

    作为旁注,我还建议更改您的代码以创建有关 Planet 的所有内容,然后将其分配到数组中:

    Planet planet = new Planet();
    planet.distance = 100 + (i * 100);
    planet.angle = 0 + (i * 20);
    planet.diameter = 20 + (i * 10);
    planet.col = colArray[i];
    // etc
    planets[i] = planet;
    

    (我还建议使用私有字段,并且可能使用接受一堆值的构造函数,但这是另一回事。)

    【讨论】:

      猜你喜欢
      • 2011-07-16
      • 1970-01-01
      • 2011-03-15
      • 2011-10-21
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      相关资源
      最近更新 更多