我正在尝试使用布尔值res做一个子手游戏,以检测用户输入的字母是否等于索引i上的单词,如果不是,则res将保持为假。 当我在单词中输入字母时,正确的字母返回true,其余字母返回false。
我的计划是减少1条生命。 仅当返回的错误数量等于单词的长度时,但我不知道如何存储返回的错误数量才能将其与单词的长度进行比较
import java.util.Scanner;
public class res{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word ="Hello";
int guessedLetters = 0;
//System.out.print(" Word has"+word.length()+" letters");
//System.out.print(" You have 9 lives left ");
while(guessedLetters
int lives = 9;
char input = in.nextLine().charAt(0);
lives =livesLeft(lives, word, input, guessedLetters);
//res = resolved(res, word, input, lives);
//Lives
//method to guess
//initial word
//what to do if letter is not correct
//what to do if letter is correct
}
}
public static int livesLeft( int lives, String word, char input, int guessedLetters) {
boolean res = false;
for(int i =0; i
if(input==word.charAt(i)) {
//System.out.print(" Your guessed the" + i +"th letter right");
res = true;
guessedLetters++;
}else {
res =false;
lives--;
}
System.out.print(res+" " + lives +" ");
}
//if res returns false on word.length() many times lives --;
//System.out.print(res+" " + lives +" ");
//System.out.println("You have"+lives+" lives left");
//System.out.println("You have guessed"+guessedLetters
//+" out of" + word.length() +" letters in the word");
return lives;
}
public static void printGameState() {
//method to print out How many letters guessed
}
}
我希望它能在用户输入正确的情况下打印True并保持int保持其原始值,而在用户输入错误的情况下则打印false并从int live减去1。 实际输入只是停留在9点的生命数
我不知道我是否理解正确。但是您有一个等于9的变量'lives'。这里的问题是您的while循环中初始化了'lives'。这意味着在每次猜测之后生命将再次变为9。要解决此问题,您可能应该在循环之前初始化变量(第9-15行):
int guessedLetters = 0;
int lives = 9;
while(guessedLetters
...
}
倒计时还存在一个问题。
在" livesLeft"方法中,您有一个for循环,该循环遍历单词的每个字母。现在,如果字母不正确,您可以减去一个。
for(int i =0; i
...
if{
...
}else {
res =false;
lives--; //
}
}
例如,单词" Hello",玩家猜到了字母" A",游戏将逐个字母地循环迭代,最终您将失去5条生命。我认为这不是您想要的。您应该在for循环之后减去这样的问题:
for(int i =0; i
...
}
lives--;
希望对您有所帮助。
while循环将设置lives=9,因此即使您的方法在下次循环时更改lives的值,生命值也将重置为9。将声明和lives的赋值移动到while之外环