0
import java.util.HashMap;
   class Room1 {
       private String description;
       private HashMap<String, Room1> dir = new HashMap<String, Room1>();
       Room1(String de) {
           description = de;
       }
       public String toString() {
           return description;
       }
       public void add(String s, Room1 r) {
           dir.put(s, r);
       }
   }
   class Game {
       Room1 lobby = new Room1("lobby");
       Room1 pub = new Room1("pub");
       lobby.add("one", pub); //syntax error
   }

When i call the add method.the eclipse tell me there are errors existing.i'm confused.i can't find the problem.

3
  • Your code that you use to call the add method needs to be inside a method or constructor, not just somewhere in the class Game. You probably forgot to add the main method there. Commented Sep 17, 2018 at 11:45
  • 2
    You can not call a method in class body directly. You need to call in a method. Commented Sep 17, 2018 at 11:46
  • 1
    Welcome to StackOverflow. When you get an error, post the exact error message - that makes it much easier to help you find out what the problem is. Error messages are there to help you find out what the problem is. Don't just say "there are errors". Commented Sep 17, 2018 at 11:54

3 Answers 3

2

You must call the methods in a function.

class Game {
    Room1 lobby = new Room1("lobby");
    Room1 pub = new Room1("pub");
    public Game() {
        lobby.add("one", pub);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Wrap the code in a method .

class Game {
   Room1 lobby = new Room1("lobby");
   Room1 pub = new Room1("pub");

   public void init(){
        lobby.add("one", pub); //syntax error
   }    
}

Comments

0

Use correct syntax

public class testing {
public static void main(String arg[]) {

    Room1 lobby = new Room1("lobby");
    Room1 pub = new Room1("pub");
    lobby.add("one", pub);
  } 
 }

2 Comments

I don't think dir should be public in Room1
@ricardofagodoy i agree..he did mistake in method calling

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.