我正在尝试解决刽子手游戏练习。刽子手游戏是随机生成一个单词并提示用户一次猜一个字母。单词中的每个字母都显示为星号。当用户做出正确的猜测时,就会显示实际的字母。当用户完成一个单词时,显示未命中数并询问用户是否继续玩另一个单词。一切都很好,直到我有一个错误,这个错误是当我运行程序时,如果啄的词是这样的(溢出)单词中的第一个“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;
}
您的where()
方法完全没有必要,这也是您的程序无法运行的原因,因为它返回了该字符第一次出现的索引。只需更换
if(guess == (char) word.charAt(i)) {
int Index_of_guess = where(guess,word);
asterisk[Index_of_guess] = guess;
}
和
if(guess == (char) word.charAt(i)) {
asterisk[i] = guess;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句