Java中房间数据拆分与结构化存储的实现咨询
Got it, let's break this down step by step. The core solution is to model each room as a dedicated Java object (so you can encapsulate all its data and access individual fields whenever you need), then write a parser to convert your raw text data into a collection of these objects. Here's how to do it:
1. Create a Room Class to Encapsulate Room Data
First, define a class that holds every property of a room. This lets you store each room's full data and pull out specific fields (like ID, description) on demand.
import java.util.Map; public class Room { private final int id; private final String name; private final String description; private final Map<String, Integer> exits; // Key: direction (e.g., "North"), Value: target room ID // Constructor to initialize all room data public Room(int id, String name, String description, Map<String, Integer> exits) { this.id = id; this.name = name; this.description = description; this.exits = exits; } // Getters for individual field access public int getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public Map<String, Integer> getExits() { return exits; } // Optional: toString method for easy debugging @Override public String toString() { return "Room{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", exits=" + exits + '}'; } }
2. Write a Parser to Convert Raw Text to Room Objects
Next, we'll build a parser that takes your raw room data, splits it into individual room entries, then extracts each field (ID, name, description, exits) using string manipulation and regex.
import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RoomParser { public static List<Room> parseRooms(String rawData) { List<Room> rooms = new ArrayList<>(); // Split raw data into individual room entries (each ends with ";") String[] roomEntries = rawData.split("(?<=;)"); for (String entry : roomEntries) { entry = entry.trim(); if (entry.isEmpty()) continue; // Extract room ID Pattern idPattern = Pattern.compile("ID=(\\d+)"); Matcher idMatcher = idPattern.matcher(entry); int id = idMatcher.find() ? Integer.parseInt(idMatcher.group(1)) : -1; // Extract room name Pattern namePattern = Pattern.compile("name\\s*=\\s*(.+?)(?=,|Description)"); Matcher nameMatcher = namePattern.matcher(entry); String name = nameMatcher.find() ? nameMatcher.group(1).trim() : "Unknown Room"; // Extract room description Pattern descPattern = Pattern.compile("Description:(.+?)(?=exits)"); Matcher descMatcher = descPattern.matcher(entry); String description = descMatcher.find() ? descMatcher.group(1).trim() : "No description available"; // Extract exits (format: "exits North 2, South 1;") Pattern exitsPattern = Pattern.compile("exits\\s*(.*?)(?=;)"); Matcher exitsMatcher = exitsPattern.matcher(entry); Map<String, Integer> exits = new HashMap<>(); if (exitsMatcher.find()) { String exitsStr = exitsMatcher.group(1); String[] exitPairs = exitsStr.split(",\\s*"); for (String pair : exitPairs) { String[] parts = pair.trim().split("\\s+"); if (parts.length == 2) { String direction = parts[0]; int targetId = Integer.parseInt(parts[1]); exits.put(direction, targetId); } } } // Add the parsed room to our collection rooms.add(new Room(id, name, description, exits)); } return rooms; } // Test the parser with your sample data public static void main(String[] args) { String rawRoomData = """ ID=1, name = Bed Room,Description:你站在一间黑暗的房间中央。这是你的房间,但感觉有些不对劲——所有东西都消失了,只剩一间空荡荡的暗室。你看到门下有红色灯光透出,似乎是一条出口。你可以从这里向北走出门。exits North 2; ID=2, name = Hallway,Description:你走进走廊,仍能看到红色灯光,但灯光来自走廊尽头。你环顾四周,发现墙上有几处破损的地方,满是类似黑洞的斑点,正慢慢吞噬着房间。其余一切都是黑灰色,和你的房间一样,但更多物品消失了。你知道走廊尽头的红光处是客厅入口。exits North 3, South 1; ID=3, name = Living-room,Description:你走进客厅,这里还残留着一些色彩,但你注意到色彩正慢慢褪去。房间中央的桌子周围摆放着两张灰色沙发。你看向东边,听到餐厅传来尖叫声,同时注意到西边通向地下室的方向有动静。exits East 4, West 5, South 2; ID=4, name = Dinning-room,Description:你走进餐厅,发现房间里有阴影在移动,感到一阵冰冷死寂的风。你持续听到尖叫声,但并非来自这个房间,而是来自东边通向院子的方向——你每靠近一步,尖叫声就更大。exits West 3, East 6; ID=5, name = Basement,Description:你走进地下室,里面空无一物,异常寒冷,你从未感受过如此低的温度。你注意到自己呼出的雾气,同时地下室每个角落的三个位置也冒出了同样的雾气。除了你进来的东边,没有其他出口。exits East 3; ID=6, name = Front-yard,Description:你走进前院,注意到草坪和堡垒周围有阴影在移动,但那里空无一人——只有你、你的花园和思绪。车道上没有汽车。你发现自己孤身一人,但可能会听到或看到异常事物。房子漂浮在无尽的虚空中,无处可去,你唯一的退路是向西返回屋内。exits West 4; """; List<Room> rooms = parseRooms(rawRoomData); // Example: Access individual fields of the Bedroom (ID=1) Room bedroom = rooms.stream().filter(r -> r.getId() == 1).findFirst().orElse(null); if (bedroom != null) { System.out.println("Bedroom ID: " + bedroom.getId()); System.out.println("Bedroom Name: " + bedroom.getName()); System.out.println("Bedroom Description: " + bedroom.getDescription()); System.out.println("Bedroom Exits: " + bedroom.getExits()); } } }
3. How to Use This Solution
- Store all rooms: The
parseRoomsmethod returns aList<Room>with all your room data. For faster lookup by ID, you can also convert this list into aMap<Integer, Room>(using room ID as the key). - Access individual fields: Use the getter methods (like
getId(),getDescription()) on anyRoomobject to pull specific data without touching the raw text. - Work with exits: The
exitsmap lets you quickly check where a room leads (e.g.,bedroom.getExits().get("North")returns2, the ID of the hallway).
内容的提问来源于stack exchange,提问作者michael murillo

