adventuredoge
adventuredoge

Reputation: 345

How to set a String value from file to a custom class variable?

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

Upvotes: 1

Views: 381

Answers (2)

Andrew
Andrew

Reputation: 49636

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
}

Upvotes: 2

Sudha
Sudha

Reputation: 220

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

Upvotes: 1

Related Questions