Java 错误数组维度缺失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35030582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:15:41  来源:igfitidea点击:

Error array dimension missing

javaarraysdimensions

提问by Chimere Ibecheozor

I keep getting array dimension missing

我不断丢失数组维度

public static Planet[] readPlanets(String filename) {

    allPlanets = new Planet[];
    In in = new In (filename);
    int nplanets = in.readInt();
    double radius = in.readDouble();
    for (int i = 0; i < allPlanets.length; i++) {
        double pxxPos = in.readDouble();
        double pyyPos = in.readDouble();
        double pxxVel = in.readDouble();
        double pyyVel = in.readDouble();
        double pmass = in.readDouble();
        String pimgFileName = in.readString();
    }
    return allPlanets;
}

Planet has six dimensions, and I have an array of multiple planets

行星有六个维度,我有多个行星的阵列

回答by null

You have to declare size of the array before you can use it's lengthattribute.

您必须先声明数组的大小,然后才能使用它的length属性。

For example:

例如:

allPlanets = new Planet[6];

回答by Jon Skeet

When you create an array, you have to specify the size. I strongly suspect you want:

创建数组时,必须指定大小。我强烈怀疑你想要:

In in = new In(filename);
int nPlanets = in.readInt();
allPlanets = new Planet[nPlanets];

Note that it's odd that you're assigning to a field and returning the reference from the method. It would be more usual to do one orthe other, e.g. use a local variable:

请注意,您分配给一个字段并从该方法返回引用是很奇怪的。做一个另一个更常见,例如使用局部变量:

Planet[] planets = new Planet[nPlanets];
...

return planets;

And then assign to the field in the calling code:

然后分配给调用代码中的字段:

allPlanets = readPlanets(...);