hao
hao

Reputation: 29

Java initialize the class

class Room {
    private String description;  
    private HashMap<String,Room> dir=new HashMap<String,Room>();

    Room(String de){
         description=de;
     }

    public String toString() {
        return description;
    }

    public void add(String s,Room r) {
        dir.put(s, r);
    }
}


class Game {
    Room lobby;   //Syntax error on token";",,expected
    lobby=new Room("pub");
} 

There are two classes.And the Game class have a problem that says Syntax error on token";",,expected.i am confused.

Upvotes: 2

Views: 3708

Answers (3)

Ori Marko
Ori Marko

Reputation: 58892

Following Java's Initializing Fields doc, there are three options:

1- Initialize on declaration:

Room lobby=new Room("pub");

2- Static Initializer blocks:

static {
    lobby=new Room("pub");
} 

3- Initializer blocks:

{
    lobby=new Room("pub");
} 

Upvotes: 1

Ganesh chaitanya
Ganesh chaitanya

Reputation: 658

Java allows initialization only during

  1. Declaration of the variable or
  2. Inside a method/block or
  3. Inside a block.

JVM allows allocation memory only during the above steps. In the example you have provided, lobby=new Room("pub"); since its in Class level JVM doesn't know how to allocate memory resulting an error.

Upvotes: 1

Yati Sawhney
Yati Sawhney

Reputation: 1402

Instead of:

Room lobby;   //Syntax error on token";",,expected
lobby=new Room("pub");

Use inline declaration and instantiation:

Room lobby = new Room("pub");

You can only have a statement inside a block of code {} (methods, static/instance blocks, other constructs that use a block) in a class.

Upvotes: -1

Related Questions