以下是海绵这个词的刽子手问题。当用户输入正确的字符(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
提交
取消