我正在尝试在java中为学校作业创建一个简单的hangman程序,我在大多数情况下都在工作。我遇到的主要问题是它会一直打印出隐藏的单词两次。它也只是通过并要求用户输入一个单词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"));
}
答案 0 :(得分:1)
使用Scanner
获取您的输入。
Scanner in = new Scanner(System.in);
String line = in.nextLine();
char input = line.charAt(0);
我认为System.in.read();
正在返回输入的字符和回车键。 (\ n char)。
这使得你的周期为每个输入运行两次,打印两次,看起来只接受8个字符。
答案 1 :(得分:0)
if (word.equals(answer[rand])) {
System.out.println("Congratulations! You guessed the word!");
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
}
else if (i == 14) {
System.out.println("Sorry, you did not guess the word.");
// Asks the user if they want to restart the application.
System.out.println("Would you like to try again? (Y/N)");
option = input();
// Returns to the main menu.
menu();
}
这并不能识别这个词是否正确。