再次猜数字游戏

时间:2017-03-28 21:33:16

标签: java

我在玩游戏时遇到问题。我有一个布尔变量但是当我输入yes或no时,程序就结束了。我无法重新启动//游戏循环。我的布尔当时没有执行任何操作

    //Game

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

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

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

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

        if (guess == number)
        {
            if (count == 1)
            {
                System.out.println("You win in " + count + " guess.");
                ++win;
                break;
            }
        }
        else if (guess > number)
        {
            System.out.println("That's too high. Try again: ");
        }
        else if (guess < number)
        {
            System.out.println("That's too low. Try again: ");
        }

    }


    //Ask to play again
    boolean isValidAnswer;
    do
    {
        System.out.print("Would you like to play again (yes/no)? ");
        String 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(!isValidAnswer);
}

}

1 个答案:

答案 0 :(得分:0)

在用户赢得不正确的猜测之前,您正在递增round,因此将其放在if块内,这意味着只有当猜测正确时它才会递增,如下所示,还会在游戏开始时将round初始化为1。

    int round = 1;
    int count = 0;
    int guess = 0;
    int win = 0;
    boolean showRound=true;
    while(win == 0) {
        if(showRound) {
            System.out.println("Round " + round);
        }
        System.out.print("What is your first guess? ");
        guess = Integer.parseInt(keyboard.nextLine());//Use scanner.nextLine()
        count++;

        if (guess == number) {
            showRound = true;
            round++;//Increment the round only after win
            System.out.println("You win in " + count + " guess.");
            ++win;
            break;
        } else if (guess > number) {
            System.out.println("That's too high. Try again: ");
            showRound=false;
        } else if (guess < number) {
            System.out.println("That's too low. Try again: ");
            showRound=false;
        }
    }