【问题标题】:Is there an alternative to a switch statement, and how would I organize this?是否有 switch 语句的替代方法,我将如何组织它?
【发布时间】:2019-05-21 19:55:41
【问题描述】:

在编写了一段时间后,我突然想到 switch 语句可能不是运行我的代码的最佳函数,例如,我不能将 case 语句简化为它们自己的方法,因为它们将是孤立的 case。我想知道是否有办法简化这段代码以及我可以用什么方法来做到这一点。

我尝试过写几个 if 语句,但是这会导致更多的混乱和无序,即使我可以将所有内容都放入他们自己的方法中。 这导致我使用 switch 语句,但是我无法简化它。

这里是一段代码。这包括总体 switch 语句和第一种情况。

while (true) //游戏循环 {

        if (user.equalsIgnoreCase("exit")) { //if player types exit at any time the game quits
            System.exit(0);
        } else { //else the game runs

            map();
            Commands(); //runs the command method
            playerDam(); //runs player damage method

            //Handles the story
            switch (question) //if question is equal to...
            {
                case "1": //introduction
                    System.out.println("Welcome to Archewind" +
                        "\nIf in need of help, press help at any time for list of commands. \nIf you would like to exit type exit at any time." +
                        "\nAre you ready to begin? \n[1]Yes\n[2]No");
                    switch (user = in .next()) //if user types one... if two...
                    {
                        case "1": //this happens
                            System.out.println("\n");
                            System.out.println("Great. Good luck");

                            question = "1.5";
                            gametic = 1;
                            break;

                        case "2": //this happens
                            System.out.println("\n");
                            System.out.println("Oh... well um... I don't really know what to do here. People usually say yes.");
                            System.out.println("\nDo you think you're ready now? \n[1]Yes \n[2]No");

                            switch (user = in .next()) {
                                case "1":
                                    System.out.println("\n");
                                    System.out.println("Ok goood, I was getting worried there for a second. Good luck.");

                                    question = "1.5";
                                    gametic = 1;
                                    break;

                                case "2":
                                    System.out.println("\n");
                                    System.out.println("Really? [1]Yes [2]No");

                                    switch (user = in .next()) {
                                        case "1":
                                            System.out.println("\n");
                                            System.out.println("This is just getting long. Do you know what you're doing to the programmer? He has to code all of this you know" +
                                                "\nIm just going to give you a choice. Either say yes next time or I am going to shut down. I mean it." +
                                                "\nStart game? \n[1]Yes \n[2]No");

                                            switch (user = in .next()) {
                                                case "1":
                                                    System.out.println("\n");
                                                    System.out.println("Alllrriiight.. Lets get this party started.");
                                                    question = "1.5";
                                                    gametic = 1;
                                                    break;


                                                case "2":
                                                    System.out.println("\n");
                                                    System.out.println("Nope. I'm done.");
                                                    user = "exit";
                                                    break;
                                            }
                                            case "2":
                                                System.out.println("Ok good. We can finally get this show on the road.");
                                    }
                            }
                            question = "1.5";
                            gametic = 1;
                            break;
                    }
                    break;

这是另一个片段。

案例“1.5”:

                    System.out.println("\nNow, before we start you need to choose a class. Each one will offer diffrent benefits.");
                    int rank = getRank();
                    userClass = RANKS[rank];
                    System.out.println("Your chosen class is: " + userClass);

                    if (userClass.equals("Farmer")) {
                        playerhealth = playerhealth + 1;
                        inv.remove("Health Potion");
                        inv.remove("Water Bottle");
                    }

                    if (userClass.equals("Trader")); {
                        inv.add("Health Potion");
                        inv.remove("Water Bottle");
                        if (playerhealth == 6) {
                            playerhealth = playerhealth - 1;
                        }
                    }

                    if (userClass.equals("Wanderer")); {
                        inv.add("Water Bottle");
                        inv.remove("Health Potion");
                        if (playerhealth == 6) {
                            playerhealth = playerhealth - 1;
                        }
                    }

                    gametic = 2;
                    question = "2";
                    break;

我预计这会比实际情况要简单得多,但我似乎无法将案例陈述分解成它们自己的方法,所以一切都更有条理。

【问题讨论】:

    标签: switch-statement code-organization case-statement


    【解决方案1】:

    在这种情况下,我的方法是编写工厂模式和命令模式。 要完成的每个“部分”工作都可以放在一个类中,该类使用一个重要方法实现接口:execute()。 如下: 接口是:

    public interface Command {
        void execute();
    }
    

    所有命令都会实现它:

    public class SayWelcomeCommand implements Command {
        @Override
        public void execute() {
            System.out.println("Welcome");
        }
    }
    

    还有另一个用于“交易者”工作的命令:

    public class TraderCommand implements Command {
        @Override
        public void execute() {
            // doing some work...
            inv.add("Health Potion");
            inv.remove("Water Bottle");
            // more work...      
        }
    }
    

    您根据已知的字符串键创建命令:

    public class CommandsFactory {
        public static Command createCommand(String commandKey) {
            switch (commandKey) {
            case 'welcome': return new SayWelcomeCommand(); break;
            case 'trader': return new TraderCommand(); break;
            case 'exit': return new ExitCommand(); break;  // todo: create that cmd..
            }
        }
    }
    

    现在,在您的 MAIN 程序中,您只需调用工厂并执行!

    while (true) {
        String commandKey =  System.in.readLine... // get from the user a command.
        Command command = CommandFactory.createCommand(commandKey);
        command.execute();
    }
    

    这样你就可以无休止地创建不同的命令,直到“exit”命令简单地关闭游戏......例如显示一条消息。

    开关只是移到了工厂,但即使在那里,您也可以通过反射从配置文件中读取类名并将它们放置在字符串到命令对象的映射中(映射键将是一个字符串,命令键。并且 Map 值将是 Command 对象)。这样您就可以从程序中完全删除 switch 的使用。

    【讨论】:

    • 您好,感谢您的回复!我不确定工厂是什么,你能解释一下吗?因此,如果我理解您的想法,我会创建几个不同的“工厂”来保存 switch 语句所做的代码。
    • 通常我们使用'new'关键字创建对象。例如:Color myFavoriteColor = new Color(127, 45, 87)。我们可以通过一个工厂方法“包装”这个对象的创建,该方法接受一个更容易记住的参数,比如颜色的名称,而不是红色、绿色、蓝色这 3 个数字......所以我们的代码看起来像这样: Color myFavoriteColor = MyColorFactory.createColor("MyFavorite") 在工厂方法中,您将像这样使用这些数字:public static Color createColor(String colorName) { if (colorName.equals("MyFavorite")) { return new Color(27, 45, 87); } }.。那是一个工厂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多