java true false_关于java:如何存储boolean返回false / true的次数

我正在尝试使用布尔值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之外环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值