嗨,我是相当新的,因为你可以看到,但我正在尝试做一个非常基本的挂人游戏。如果用户猜测是正确的,我想制作一系列他到目前为止所拥有的信件。但我得到的只是阵列中保存的最后一个键盘输入。
这是代码。
do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();
String [] GuessedWordSoFar = new String[wordToGuess.length()];
char[] wordToGuessInCharArray = wordToGuess.toCharArray();
if((new String(wordToGuessInCharArray).contains(firstGuess))){
int index = -1;
char c = firstGuess.charAt(0);
for(int z = 0; (z <wordToGuessInCharArray.length)&&
(index == -1); z++){
if( wordToGuessInCharArray[z] == c) {
index = z;
System.out.println("Correct");
GuessedWordSoFar[index] = firstGuess;
}
}
System.out.println(Arrays.asList(GuessedWordSoFar));
}
答案 0 :(得分:1)
问题是GuessedWordSoFar数组的初始化在do-while循环中,因此每次循环执行时它都会被重置。 尝试下面的代码,这应该可以解决您的错误。
String [] GuessedWordSoFar = new String[wordToGuess.length()];
do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();
char[] wordToGuessInCharArray = wordToGuess.toCharArray();
if((new String(wordToGuessInCharArray).contains(firstGuess))){
int index = -1;
char c = firstGuess.charAt(0);
for(int z = 0; (z <wordToGuessInCharArray.length)&&
(index == -1); z++){
if( wordToGuessInCharArray[z] == c) {
index = z;
System.out.println("Correct");
GuessedWordSoFar[index] = firstGuess;
}
}
System.out.println(Arrays.asList(GuessedWordSoFar));
}