每当我的用户正确猜到这个词时,我都无法弄清楚如何终止循环。
我可以做这样的事情,或者使用子字符串函数逐个取出单词的字母。
这是我到目前为止所做的:
package mcneil;
import java.util.Scanner;
import java.util.Random;
public class HangmanGame
{
public static void main(String[] args)
{
Scanner ui = new Scanner(System.in);
Random rnd = new Random();
String words[] = {"Mac", "Windows", "DOS", "Linux", "Solaris"};
String man[] ={" ______\n"
+ " | |\n"
+ " |\n"
+ " |\n"
+ " |\n"
+ "_____",
" ______\n"
+ " | |\n"
+ " | O\n"
+ " |\n"
+ " |\n"
+ "_____",
" ______\n"
+ " | |\n"
+ " | O\n"
+ " | |\n"
+ " |\n"
+ "_____",
" ______\n"
+ " | |\n"
+ " | O\n"
+ " | |/\n"
+ " |\n"
+ "_____",
" ______\n"
+ " | |\n"
+ " | O\n"
+ " | \\|/\n"
+ " |\n"
+ "_____",
" ______\n"
+ " | |\n"
+ " | O\n"
+ " | \\|/\n"
+ " | /\n"
+ "_____",
" ______\n"
+ " | |\n"
+ " | O\n"
+ " | \\|/\n"
+ " | / \\\n"
+ "_____"};
String guess;
int guesses = 0;
String guessedLetters = " ";
boolean wordGuessed = false;
System.out.println(man[0]);
String answer = words[rnd.nextInt(words.length)];
System.out.println("I'm thinking of a word that contains "
+ answer.length() + " letters\n");
do
{
for(char letter : answer.toCharArray())
{
if(guessedLetters.indexOf(letter)== -1)
{
System.out.print('*');
}
else
{
System.out.print(letter);
}
}
System.out.println("\nPlease enter a letter: ");
guess = ui.next();
guessedLetters += guess + " ";
System.out.println("You have guessed the letters: "
+ guessedLetters);
// not a good guess
if(!answer.contains(guess))
{
System.out.println(man[guesses + 1]);
guesses++;
//some kind of counter
}
else {
}if(answer.length() == 0)
{
wordGuessed = true;
}
}while(!wordGuessed && guesses < 6);
}
}
答案 0 :(得分:0)
您有条件表明单词中是否包含猜测,以及答案中的字母是否在猜测字母中。你需要一些跟踪答案是否完整的东西。也许你可以计算猜测答案的非*字母。或者还有其他方法。