我正在嘗試解決劊子手游戲練習(xí)。劊子手游戲隨機(jī)生成一個單詞并提示用戶一次猜一個字母。單詞中的每個字母都顯示為星號。當(dāng)用戶做出正確的猜測時,就會顯示實(shí)際的字母。當(dāng)用戶完成一個單詞時,顯示未命中的次數(shù)并詢問用戶是否繼續(xù)玩另一個單詞。一切都很好,直到我有一個錯誤這個錯誤是當(dāng)我運(yùn)行程序時如果被啄的單詞是這樣的(溢出)單詞中的第一個'O'出現(xiàn)但第二個'O'不會'導(dǎo)致程序可以' t 區(qū)分兩者。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;}
1 回答

三國紛爭
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個贊
您的where()
方法是完全沒有必要的,也是您的程序無法運(yùn)行的原因,因?yàn)樗祷亓俗址谝淮纬霈F(xiàn)的索引。只需更換
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; }
添加回答
舉報(bào)
0/150
提交
取消