有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助创建一个“help”命令,用户可以在任何时候键入该命令,查看关键字,或者在遇到问题时获得帮助

我正在为我的AP计算机科学期末项目创建一个基于文本的RPG,我想这样做,玩家可以在任何时候键入“help”,并在控制台中显示一条消息。我能想到的唯一方法是使用扫描仪导入并执行以下操作:

    String help = scan.nextLine();
    switch(help) {
        case help:
        System.out.println("help message");
        break;
}

我一直在为这个项目自学Java,我是个新手,我知道这可能是一个非常低效的方法,更不用说它只能在1点上工作。因此,如果有人能给我指出正确的方向,我将永远感激。 另外:在提交这篇文章之前,我已经搜索了答案,但是我找不到一个描述如何在整个游戏过程中将其打印到控制台的答案


共 (3) 个答案

  1. # 1 楼答案

    如果。。埃利夫。。然后使用语句来捕获命令,而不是switch语句。别忘了用绳子。equals()方法来比较字符串!看看为什么

    String cmd = scan.nextLine();
    if(cmd.equals("help")) {
        System.out.println("help message");
    } else if(cmd.equals("move")) {
        System.out.println("move");
    } else {
        System.out.println("I'm sorry, I did not understand that command :(")
    }
    
  2. # 2 楼答案

    您可以创建一个处理请求帮助的方法,您将始终使用该方法而不是scan.nextLine()

    public static String getNextLine(Scanner scan) {
        String str = scan.nextLine(); //Get the next line
        if (str.equals("help") { //Check whether the input is "help"
            System.out.println(/* help */); //if the input is "help", print your help text
            return getNextLine(scan); //try again.
        else {
            return str; //return the inputted string
        }
    }
    

    现在,无论在哪里使用scan.nextLine,都要使用getNextLine(scan)。这样,当用户输入“帮助”时,您将自动计算。(只是一个提示,您可能想使用equalsIgnoreCase而不是equals,这样,如果用户键入“Help”,您的代码仍然有效。)

  3. # 3 楼答案

    除了HelperFormatter之外,我还会使用Apache Commons CommandLine类:

    private static final String HELP = "help";
    private static final String SOME_OTHER_TOGGLE = "toggle";
    
    /**
     * See  help for command line options.
     */
    public static void main(String[] args) throws ParseException {
        Options options = buildOptions();
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);
    
        if (line.hasOption(HELP)) {
            printHelp(options);
        }
    }
    
    private static void printHelp(Options options) {
        String header = "Do something useful with an input file\n\n";
        String footer = "\nPlease report issues at http://example.com/issues";
    
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("myapp", header, options, footer, true);
    }
    
    private static Options buildOptions() {
        Options options = new Options();
        options.addOption(OptionBuilder
            .withLongOpt(SOME_OTHER_TOGGLE)
            .withDescription("toggle the foo widget in the bar way")
            .create()
        );
        options.addOption(OptionBuilder
            .withLongOpt(HELP)
            .withDescription("show the help")
            .create()
        );
    
        // ... more options ...
    
        return options;
    }