0

I am trying to declare an Array of Rectangles in java but I can't figure out how. 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; initializing it is the problem. How can I fix this error?

3
  • Would you rather do the initialisation inside a method, or inside the constructor of whatever class this is? It is possible to do it as an "initialisation block" by enclosing your second line in { } characters, but it's probably not what you want to do. Commented Nov 9, 2014 at 21:24
  • Are you saying i should initialize the rectangles inside the class constructer? Commented Nov 9, 2014 at 21:29
  • It's hard to say what you "should" do, without knowing what you're actually trying to build here. But it would help you over the error. Commented Nov 9, 2014 at 21:31

1 Answer 1

1
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).
In your case, you mixed field (as suggested by your private keyword) with computation, leading to the compilation error you got.

You may want to do:

MyClass {

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

     MyClass() {
      rectArray[0] = new Rectangle(0,0,0,0);
     }
   }
Sign up to request clarification or add additional context in comments.

4 Comments

wait i'm confused can you explain it a little better? What is different between my code and yours?
private is used for annotating an object's field, not a local variable. You cannot write some "process" directly on the class. You have to wrap it in a constructor, initialisation block or method. Indeed, this line: rectArray[0] = new Rectangle(0,0,0,0); is what I called a "process", since you use data (the array) your initialized. All the init process concerning a field should be inlined, that is not your case.
"Why cant youn initialize outside a method or constructor?" => that's how Java was designed by its creator.
I would use Rectangle[] var = instead of Rectangle var[]. It makes it clear that it's an array of Rectangle objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.