首页 > 解决方案 > 如何将同义词添加到 Java 中的 switch 语句?

问题描述

我有下面的功能,我想为每个案例添加同义词,例如案例“北”也可能是“上”,案例“东”可能是正确的等等。由于所有案例都属于同一个 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;
            }
        }

标签: javasynonym

解决方案


只需列出这样的案例:

switch (input[1]) {
            case "north": case "up":
            case "east": case "right":
            case "south": case "down":
            case "west": case "left":

推荐阅读