再次实现播放布尔值

时间:2017-04-03 20:44:09

标签: java

我想知道如何实现我的布尔playAgain。我知道目前它没有做任何事情,它只是无用的代码。但我不知道如何将它变成一个能让我的游戏再次发挥作用的功能。我上次没有得到答案。

    System.out.println("Guess a number between 1-100.");

    Scanner keyboard = new Scanner(System.in);
    Random rand = new Random();
    int number = rand.nextInt(100)+1;
    int round = 1;
    int count = 0;
    int guess = 0;
    int win = 0;
    int loss = 0;
    String playAgain = "";

    //Code for the game itself

do
{
    while(win == 0)
    {
        if (count == 0)
        {
            System.out.println("Round " + round);
            System.out.println("-------");

            System.out.println("Secret " + number);

            System.out.print("What is your first guess? ");
            guess = keyboard.nextInt();
            count++;
        }

        //User Guess is correct
        if (guess == number)
        {
            break;
        }

        //Round limit reached
        if (count == 7 && guess != number)
        {
            ++loss;
            break;
        }

        //User Guess is too high
        if (guess > number)
        {
            System.out.print("That's too high. Try again: ");
            guess = keyboard.nextInt();
            count++;
        }

        //User Guess is too low
        if (guess < number)
        {
            System.out.print("That's too low. Try again: ");
            guess = keyboard.nextInt();
            count++;
        }
}
        boolean isValidAnswer;
        System.out.print("\nWould you like to play again (yes/no)? ");
        playAgain = keyboard.next().toUpperCase();
        isValidAnswer= playAgain.equals("YES") || playAgain.equals("NO");
        if(! isValidAnswer)
        {
            System.out.println("Error: Please enter yes or no");
            System.out.println();
        }
} while(playAgain.equals("YES"));


    //If user wins
    //Count = 1 word is guess
    if (guess == number)
    {
        if (count == 1)
        {
            round++;
            System.out.println("You got it in " + count + " guess.");
            ++win;
        }
   }

2 个答案:

答案 0 :(得分:0)

你可以这样做:

  boolean status = true;


if(win > 0 ){

System.out.print("Would you like to play again (true/false)? ");
System.out.println();
System.out.println("Error: Please enter true or false");
String input = scan.nextLine();


if(status != input){

// do not do anything  or close the program.
} 
else {

// do something cause players wants to play again.
 }
}

答案 1 :(得分:0)

你可以做点像......

Scanner in = new Scanner(System.in);
String playAgain = "no";
do {

    // game logic

    System.out.println("Want to play more (yes/no) ?");
    playAgain = in.nextLine();
} while(playAgain.equals("yes") || playAgain.equals("YES"));