I've a file with a line that looks like this "Room,home,You are in your home"
I wanna read the file and then create an object (I have created a class called Room), what I wanna do now is like read the line and creat something like this.
Room home = new Room (You are in your home)
I have used bufferedreader and split my words and put them in an ArrayList but it just doesn't look right. I need help cuz I don't know how to continue.
BufferedReader myfile = new BufferedReader(new FileReader(thefile));
String line = thefile.readLine();
while (line != null) {
String[] array = line.split(",");
line = file.readLine();}
CodePudding user response:
Your array should look like this:
array = ["Room", "home", "You are in your home"]
However. You can not run something like this:
array[0] array[1] = new array[0](array[2]);
Therefor you should use some conditions to eventually add more places.
if (array[0].equals("Room") {
Room room1 = new Room(array[2]);
}
Or maybe create it as a switch:
switch(array[0]) {
case "Room": ...
case "Staircase": ...
...
}
My advice would be to use a class called Room to store aditional information (just like "home") as description. As @Rogue said: There is no "clean" way use "home" as a name for a variable.
CodePudding user response:
you can do something like this
class Test{
public static void test( )throws ParseException {
String line = "Room,home,You are in your home";
String parts[] = line.split(",");
String objectType = parts[0];
String objectName = parts[1];
String objectParameter = parts[2];
Map<String, Room> roomMap;
if(objectType.equals("Room")){
roomMap = new HashMap<>();
roomMap.put(objectName, new Room(objectParameter));
System.out.println(roomMap.get(objectName).description);
}
}
}
class Room{
public String description;
public Room(String description){
this.description = description;
}
}