所以,我成功地制作了一个非常简单但完整的刽子手版本。现在我想改进程序并慢慢添加功能(最终我想要的图形)。我想要修复的第一件事就是重复字母,此时,如果用户决定键入相同的字母(单词中的一个字母)与单词的长度一样多,他们就会得到虚假的“胜利”。什么是阻止这种情况发生的最好方法?
PS。我是编程的新手,这个项目对我来说真的很难......所以如果答案真的很明显,对不起要问,我今晚再也想不到了。
任何帮助将不胜感激,这是我的代码:
import java.io.*;
public class hangman_test2
{
public static void main(String[] args) throws IOException
{
BufferedReader in;
in = new BufferedReader (new InputStreamReader (System.in));
boolean Lets_play=true;
String response;
while (Lets_play)
{
printheader();
String the_word=getWord();
System.out.println(the_word);
print_blanks(the_word);
guesses(the_word);
System.out.println("Want to play again?");
response=in.readLine();
if(response.charAt(0)=='n' || response.charAt(0)=='N')
{
Lets_play= false;
System.out.println("Thanks for playing!");
}
}
}//end main
public static void printheader()
{
System.out.println("Welcome, lets play hangman!");
System.out.println("enter letters to guess the word\n");
}//end print header
public static String getWord()
{
String [] possible_word=new String [10];
possible_word[0]="green";
possible_word[1]="orange";
possible_word[2]="tree";
possible_word[3]="flowers";
possible_word[4]="ocean";
possible_word[5]="grudge";
possible_word[6]="scraple";
possible_word[7]="crab";
possible_word[8]="insect";
possible_word[9]="stripes";
String theWord= possible_word [(int)(Math.random()*possible_word.length)];
return theWord;
}//end the word
public static void print_blanks(String the_word)
{
for (int x=0; x<the_word.length(); x++)
{
System.out.print("_ ");
}
}//print blanks
public static void guesses(String the_word)throws IOException
{
BufferedReader in;
in = new BufferedReader (new InputStreamReader (System.in));
boolean thisRound=true;
int strike=0;
int right_letter=0;
while (thisRound)
{
int letters_not_in_word=0;
char letter_guessed=in.readLine().charAt(0);
for (int current_letter=0; current_letter<the_word.length(); current_letter++)
{
if (the_word.charAt(current_letter)==letter_guessed)
{
System.out.println(letter_guessed + " fits in space number " + (current_letter+1));
right_letter++;
if(right_letter == the_word.length())
{
win(the_word);
thisRound=false;
}
}
else
{
letters_not_in_word++;
if (letters_not_in_word==the_word.length())
{
System.out.println(letter_guessed + " is not in the word");
strike ++;
if(strike==5)
{
lose(the_word);
thisRound=false;
}
}//if
}//else
}//for
}//while
}//end guesses
public static void win( String word)
{
System.out.println("\ncongradulations, you won!");
System.out.println("the word is " + word + "\n");
}
public static void lose( String word)
{
System.out.println("\nsorry, you lost");
System.out.println("the word is " + word + "\n");
}
}
答案 0 :(得分:4)
查看HashSet和Set界面。 Set的作用是防止两次添加同一个对象。
因此,每次用户添加一个字母时,请检查它是否已在该集合中。如果不是,那么检查他们的猜测并将其添加到集合中。如果它已经在集合中,那么忽略他们的猜测。