以下是海綿這個詞的劊子手問題。當用戶輸入正確的字符(s,p,o,n,g,e)時,數組隱藏[]會正確更新(將_替換為正確的字符)。但是,當用戶輸入不正確的字符時,它會顯示隱藏 [],其中包含所有 _ _ _ _ _ _ _任何提示都值得贊賞!謝謝package javaapplication3;import java.util.Scanner;public class JavaApplication3 { public static void main(String[] args) { String secretWord = "sponge"; int lettersLeft = secretWord.length(); int attempts = 6; int position = 0; //Index of found character in string char[] hidden = new char[secretWord.length()]; //Array of hidden chars //Display initial hidden array for(int i=0; i < secretWord.length(); i++) { hidden[i] = '_'; System.out.print(hidden[i] + " "); } do{ System.out.println(""); System.out.println("Attempts left = " + attempts); System.out.println("Enter a letter to guess the word: "); //User enters character Scanner scan2 = new Scanner (System.in); char test = scan2.next().charAt(0); //Search string secretWord if char test is in it if(secretWord.contains(Character.toString(test))) { position = secretWord.indexOf(test) +1; //System.out.println("Letter is in position: " + position); lettersLeft--; } else { position = 0; attempts--; } //Update hidden array with _ or correct char for(int i=0; i < secretWord.length(); i++) { if (position == 0) { hidden[i] = '_'; } else if (position != 0) { hidden[position-1] = test; } System.out.print(hidden[i] + " "); } }
1 回答

catspeake
TA貢獻1111條經驗 獲得超0個贊
如果輸入不正確,您可以重寫整個數組 - 在顯示其內容的同一循環中。我不知道你為什么這樣做。hidden_
您要做的是只在 中更新正確的猜測,并在不正確的猜測時保持原樣。hidden
例如,替換以下內容:
//Update hidden array with _ or correct char
for(int i=0; i < secretWord.length(); i++)
{
if (position == 0)
{
hidden[i] = '_';
}
else if (position != 0)
{
hidden[position-1] = test;
}
System.out.print(hidden[i] + " ");
}
與此:
if (position != 0) {
hidden[position - 1] = test;
}
for (int i = 0; i < secretWord.length(); i++) {
System.out.print(hidden[i] + " ");
}
添加回答
舉報
0/150
提交
取消