需要帮助创建用户可以随时键入的 "help" 命令,并在遇到困难时查看关键字或获取帮助



我正在为我的AP计算机科学最终项目创建一个基于文本的RPG,我想让它在任何时候玩家都可以输入"帮助",它会在控制台中显示一条消息。我能想到的唯一方法是使用扫描仪导入并执行以下操作:

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

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

您可以创建一个处理寻求帮助的方法,您将始终使用它而不是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这样,如果用户键入"帮助",您的代码仍然有效。

使用巨人 if..埃利夫..then 语句来捕获命令,而不是 switch 语句。不要忘记使用 String.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 :(")
}

除了 HelperFormatter 之外,我还将使用 Apache Commons 命令行类:

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 filenn";
    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;
}

相关内容

最新更新