1

I'm trying to instantiate a String object that I read from a file and then set the value of that object as an object of a custom class (Room). Any advice on how I can do that?

This is what I have so far:

String roomName = scanner.hasNext() ? scanner.next() : "";
//scanning the name of the room from file
  if(room == "room"){
     Room roomName = new Room(roomName);
   }

So basically, I'm trying to set the roomName string that I read from the file, and then set that same value as the name of the Room object.

EDIT: the file that I'm trying to read will have either a "door" value or a "room" value, which is why I check if the value is a "room" or not.

The Room class is instantiated like so:

Room room0 = new Room(0);

The sample file I read is something like this:

room 0 wall wall wall
door d0 0 1 close
adventuredoge
  • 345
  • 5
  • 17
  • What's wrong with the above code? – Jonathan Lam Nov 06 '15 at 20:11
  • 1
    What is your if-statement trying to check? (apart from the fact that that is not how you compare strings in java) – azurefrog Nov 06 '15 at 20:11
  • Sorry but what is the problem you are facing? What are you trying to achieve? To be honest your question reminds [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Pshemo Nov 06 '15 at 20:16
  • 2
    this is not a duplicate of that question. he doesn't have a infinite set of parameters, he has `(if input.contains("room")) myRoom = new Room(roomName)` – jb. Nov 06 '15 at 20:31

2 Answers2

2

By your logic:

String roomName = scanner.hasNext() ? scanner.next() : "";
Room room = null;

if(roomName.equals("room")) {
   room = new Room(roomName);
}

By my logic (nothing to check):

Room room = new Room(scanner.hasNext() ? scanner.next() : ");

EDIT:

List<Room> rooms = new ArrayList<>();
...
if (roomName.equals("room")) {
    rooms.add(new Room(rooms.size())); // rooms.get(0) = room with number 0
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

This is not possible in Java. You can't use variable value (value of roomName) as another variable name.

Sudha
  • 220
  • 2
  • 16
  • "not possible" may be too strong words. Depending on what OP is trying to achieve `Map` may be quite nice solution. – Pshemo Nov 06 '15 at 20:20