【发布时间】:2021-05-15 12:40:27
【问题描述】:
我有下面的功能,我想为每个案例添加同义词,例如案例“北”也可能是“上”,案例“东”可能是正确的等等。因为所有案例都属于同一个 try/catch声明我不确定如何针对每个特定案例做到这一点。感谢任何帮助!谢谢
public void changeRoom(boolean isValidInput, String[] input, int attemptCount) {
while (isValidInput) {
switch (input[1]) {
case "north":
case "east":
case "south":
case "west":
try {
if (world.getCurrentRoom().roomExits.containsKey(input[1])) {
player.setMostRecentExit(input[1]);
world.setCurrentRoom(world.getCurrentRoom().roomExits.get(input[1]));
isValidInput = false;
if (isSound) {
walkEffect.playSoundEffect();
}
Thread.sleep(1800);
narrateRooms(world.getCurrentRoom().getDescription());
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
default:
System.out.println("You hit a wall. Try again: ");
System.out.print(">>>");
attemptCount++;
if (attemptCount >= 2) {
System.out.println();
openMap();
System.out.println("Where would you like to go? ");
System.out.print(">>>");
}
input = scanner.nextLine().strip().toLowerCase().split(" ");
break;
}
}
【问题讨论】:
-
相同的机制,或者可能更好,通过某种规范器运行输入。请注意,“向上”仅适用于 2d 世界中的北方。
-
您可以定义同义词映射,例如
Map.of("up", "north", "right", "east" /* etc */),然后打开例如map.getOrDefault(input[1].toLowerCase(), input[1].toLowerCase())而不是