如何存储并布尔多少次返回false /真

问题描述 投票:-2回答:2

我试图让使用布尔资源来检测,如果用户输入字母为索引i等于字刽子手游戏,如果它不是资源将保持假。当我在我的字里的一封信,多数民众赞成类型,返回上正确的字母和虚假的休息真实。

我的计划是到零下1条生命。只有当返回的错误数量等于字的长度,但我不知道如何存储的假(S)的数量,以便将其比作字的长度返回

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<word.length()) {

            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<word.length();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

    }

}

我希望它打印真,并保持住INT在它的原单值,如果用户输入是正确的,打印假,减去1从int生活,如果用户输入错误。实际的输入停留在9人的生命只是数量

java boolean storing-data
2个回答
1
投票

我不知道如果我理解你的权利。但是,你有一个变量的生命“,这等于9.这里的问题是你有你的生活'while循环内初始化。每一个生命的猜测后,这意味着将再次9.要解决这个问题,你应该循环(9-15行)之前可能初始化变量:

int guessedLetters = 0;
int lives = 9;

while(guessedLetters<lives) {
  ...
}  

也将有与倒计数的生活问题。在该方法中“livesLeft”你有一个for循环,通过每一个字的一封信,迭代。而现在,你减一周后,如果信是不正确的。

for(int i =0; i<word.length();i++) {
   ...
   if{
      ...
   }else {
      res =false;
      lives--; // <--- right here
   } 
}

例如,这个词是“你好”和玩家猜测字母‘A’。该游戏将通过每一个字母一个迭代。最后,你将失去5周的生活。我想,这是不是你想要的。为了解决这个问题问题后,对于像这样的循环,你应该减:

for(int i =0; i<word.length();i++) {
   ...
}
lives--;

我希望这是对你有点帮助。


0
投票

您的while循环设置lives=9所以即使你的方法改变了lives下一次9.值在循环恶有恶报的生命值被重置移动你的声明和分配lives到您的while循环外

© www.soinside.com 2019 - 2024. All rights reserved.