T. Thomas
T. Thomas

Reputation: 680

Adding Objects to a Vector in Java

I'm trying to add a Objects to a vector be when I use the Code Pasted below I get errors that says "Syntax error on token(s), misplaced construct(s)." and "Syntax error on token "gamePaddle", VariableDecloratorID Expected after this token." I've looked everywhere and can't find what I'm doing wrong they all tell me to construct the Vector like this. The error happens on the line that starts ListOfGameObjects.add(...

class GameWorld {
/**
 * Code that instantiate, hold, and manipulate GameOobjects and related game state data.
 * @author Tyler Thomas
 *
 */
        Paddle gamePaddle = new Paddle();
        Ball gameBall = new Ball();
        Edge topEdge = new Edge(50, 150);
        Edge bottomEdge = new Edge(50, 0);
        Edge leftEdge = new Edge(0, 75);
        Edge rightEdge = new Edge(100, 75);
        Vector<GameObject> ListOfGameObjects = new Vector<GameObject>();
        ListOfGameObjects.add(gamePaddle);
}

Upvotes: 0

Views: 8368

Answers (2)

mikera
mikera

Reputation: 106351

You're trying to add a statement within a class declaration.

You need to put this inside a code block, e.g. inside a constructor:

class Gameworld {
  ....

  public GameWorld() {
    ListOfGameObjects.add(gamePaddle);
  }

}

If you do the above, the padde will be added to the ListOfGameObjects when the GameWorld object is constructed.

P.S. you should also probably rename it "listOfGameObjects". The initial capital letter is usually reserved for class names. This is a useful convention that will make your code easier to read / understand.

P.P.S. You should also consider replacing the Vector with ArrayList. Vector is considered a bit outdated nowadays.

Upvotes: 5

Mihir Mathuria
Mihir Mathuria

Reputation: 6539

Any non-instantiating code, like ListOfGameObjects.add(gamePaddle); needs to be inside a method.

For a simple example like this one, put all your code inside public static void main

Upvotes: 5

Related Questions