繁体   English   中英

再次猜数字游戏

[英]Number guessing game play again

我在重新玩游戏时遇到了问题。 我有一个布尔变量但是当我输入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);
}

}

您在用户赢得不正确的猜测之前递增该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;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM