简体   繁体   English

如何在Java中初始化数组?

[英]How do I initialize an array in Java?

I am trying to declare an Array of Rectangles in java but I can't figure out how. 我试图在Java中声明一个Rectangles Array ,但我不知道如何。 Here is my code: 这是我的代码:

private Rectangle rectArray[] = new Rectangle[9];
rectArray[0] = new Rectangle(0,0,0,0);

I tried commenting out the second line and it works fine, but when I leave the second line in, it has the error: 我尝试注释掉第二行,它正常工作,但是当我将第二行留在其中时,出现错误:

Syntax error on token ";" expected {

It's not declaring the Array that's the problem; 不是在声明Array是问题;而是在声明Array initializing it is the problem. 初始化是问题所在。 How can I fix this error? 如何解决此错误?

private Rectangle rectArray[] = new Rectangle[9];
rectArray[0] = new Rectangle(0,0,0,0);

You have to initialize within constructor (generally constructor (or even initilisation block) than method for init). 您必须在构造函数中进行初始化(通常是构造函数(甚至是初始化块),而不是init的方法)。
In your case, you mixed field (as suggested by your private keyword) with computation, leading to the compilation error you got. 在您的情况下,您将字段(由private关键字建议)与计算混合在一起,从而导致编译错误。

You may want to do: 您可能想要做:

MyClass {

     private Rectangle rectArray[] = new Rectangle[9];

     MyClass() {
      rectArray[0] = new Rectangle(0,0,0,0);
     }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM