gpt4 book ai didi

java - Hangman 代码问题 (Java)

转载 作者:行者123 更新时间:2023-12-01 12:20:35 31 4
gpt4 key购买 nike

我正在尝试用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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com