我正在尝试解决刽子手游戏练习。刽子手游戏随机生成一个单词并提示用户一次猜一个字母。单词中的每个字母都显示为星号。当用户做出正确的猜测时,就会显示实际的字母。当用户完成一个单词时,显示未命中的次数并询问用户是否继续玩另一个单词。一切都很好,直到我有一个错误这个错误是当我运行程序时如果被啄的单词是这样的(溢出)单词中的第一个'O'出现但第二个'O'不会'导致程序可以' t 区分两者。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char again = 'y' ;
int missed = 0;
String[] words = {"computer" , "programming" , "web" , "android"};
do{
String word = words[(int)(Math.random()*4)];
int size = word.length();
char[] asterisk = new char[size];
for(int i=0; i<size; i++){
asterisk[i] = '*';
}
do{
System.out.print("(Guess) Enter a letter in word ");
for(int i=0; i<asterisk.length; i++) System.out.print(asterisk[i]);
char guess = input.next().charAt(0);
for(int i=0; i<asterisk.length; i++){
if(guess==(char)word.charAt(i)){
int Index_of_guess=where(guess,word);
asterisk[Index_of_guess]=guess;
}
else missed++;
}}while(check(asterisk));
System.out.print("The word is ");
for(int i=0; i<asterisk.length; i++) System.out.print(asterisk[i]);
System.out.println(" You missed " + missed + " time");
if(missed>1)
System.out.print("s");
System.out.println("Do you want to guess another word? Enter y or n > ");
again = input.next().charAt(0);
}while(again=='y');
}
public static boolean check(char[] asterisk){
for(int i=0; i<asterisk.length; i++){
if(asterisk[i]=='*')
return true;
}
return false;
}
public static int where(char guess, String word){
for(int i=0; i<word.length(); i++){
if(guess== word.charAt(i))
return i;
}
return 0;
}
三国纷争
相关分类