java - Hangman 代码问题 (Java)

标签 java

我正在尝试用java为学校作业创建一个简单的刽子手程序,并且我已经让它大部分工作了。我遇到的主要问题是它不断打印出隐藏的单词两次。它还只要求用户输入一个单词 8 次,而实际上应该是 15 次。有人能告诉我哪里出错了吗?

// Its in a separate method.
public static void application1() throws Exception {
    // Tells the user about the game.
    System.out.println("Welcome to Hangman!");
    System.out.println("Please try to guess the word within 15 letters.");

    String option = "";

    // Creates a array of all the phrases.
    String answer[] = new String[20];
    answer[0] = "computer";
    answer[1] = "radio";
    answer[2] = "calculator";
    answer[3] = "teacher";
    answer[4] = "bureau";
    answer[5] = "police";
    answer[6] = "geometry";
    answer[7] = "president";
    answer[8] = "subject";
    answer[9] = "country";
    answer[10] = "environment";
    answer[11] = "classroom";
    answer[12] = "animals";
    answer[13] = "province";
    answer[14] = "month";
    answer[15] = "politics";
    answer[16] = "puzzle";
    answer[17] = "instrument";
    answer[18] = "kitchen";
    answer[19] = "language";

    do {
        // Creates a random number to choose which word to choose from.
        int rand = (int)(Math.random() * 20 + 0);

        StringBuffer word = new StringBuffer("");

        // This makes the unknown word as long as the actual word.
        for (int i = 0; i < answer[rand].length(); i++) {
            word.append("_");
        }

        System.out.println(word);

        char input = ' ';

        // This is where it checks the input and replaces the letters.
        for (int i = 0; i < 15; i++) {
            input = (char) System.in.read();

            for (int j = 0; j < answer[rand].length(); j++) {
                if (input == answer[rand].charAt(j)) {
                    word.setCharAt(j, input);
                }
            }

            // This is where the hidden word get printed twice.
            System.out.println(word);
        }

        // Asks the user if they want to restart the application.
        System.out.println("Would you like to try again? (Y/N)");
        option = input();

    } while (option.equalsIgnoreCase("y"));
}

最佳答案

使用扫描仪获取您的输入。

Scanner in = new Scanner(System.in);
String line = in.nextLine();
char input = line.charAt(0);

我认为System.in.read();正在返回输入的字符和回车键。 (\n 字符)。

这使得你的循环为每个输入运行两次,打印两次,看起来只接受 8 个字符。

关于java - Hangman 代码问题 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689683/

相关文章:

java - 我有一个函数,在其中我正在使用匿名类运行一个线程,那么如何将值返回给该函数

java - 什么是 xdoclet? (从C程序员的角度来看)

java - 如何从 Java 运行 Node.js 进程?

带有 dexguard 的 Java 库

java - Hi-Lo 猜谜游戏 - 限制用户输入的尝试次数和重玩逻辑

java - Spring security - 具有多个身份验证提供者的记住我身份验证

Java线程不会停止/中断

Java - 如果在组合框1中选择了一个值,那么应该在所有其他组合框中禁用它

java - JSqlParser 如何拆分一个表达式

java - 是否可以加快 Maven Artifact 的下载速度?