制作HiLo程序〜无法重复游戏

时间:2016-10-05 17:14:34

标签: java

所以,对于我的Java课程,我需要制作一个HiLo游戏。我认为这个游戏是我自己的,但我想更进一步,在用户完成游戏(猜对了正确的数字)后,我想问他们是否想再玩一次。 问题是,我似乎无法弄清楚具体如何。我尝试了几件事,目前我试图让他们进入是或否继续玩游戏。如果有人能帮助我弄清楚我做错了什么并向我解释,那就太好了。谢谢!

    Random generator = new Random();
    Scanner scan = new Scanner(System.in);
    int answer, guess; 


    answer = generator.nextInt(101);
    System.out.println("Lets play a game. Guess the number(0-100): ");
    guess = scan.nextInt();

    while (guess != answer){
        System.out.println("Wrong guess.");
        if (guess > answer){
            System.out.println("Your guess was higher than the answer. Guess again: ");
        }
        else{
            System.out.println("Your guess was lower than the answer. Guess again: ");
        }
        guess = scan.nextInt();
    }
    if (guess == answer)
        System.out.println("You got it! The number was " + answer);

    //after initial game finishes, we ask if they want to play again.
    System.out.print("Want to play again? ");
    String again = scan.nextLine();

    while (again != "no"){
    System.out.println();
    System.out.print("Great! lets play again.");
    System.out.println("Take a guess(0-100 inclusive): ");
    guess = scan.nextInt();
    while (guess != answer){
        System.out.println("Wrong guess.");
        if (guess > answer){
        System.out.println("Your guess was higher than the answer. Guess again: ");
    }
        else{
        System.out.println("Your guess was lower than the answer. Guess again: ");
    }
    guess = scan.nextInt();

    if (guess == answer)
        System.out.println("Your got it! The number was " + answer);

    System.out.println("Want to play again? (0 for no, 1 for yes): ");
    again = scan.nextLine();
    }
    }
    System.out.println("Thanks for playing!");
}

}

1 个答案:

答案 0 :(得分:0)

!=运算符不检查两个字符串是否包含相同的字符。你想要做的是:

while (again.equals("yes")) {
  ...
}

你还应该尝试将你的游戏代码放在另一个循环中,所以在游戏结束时(仍然在循环内),你可以询问玩家是否想再玩一次。如果是,则必须再次执行循环,否则它将停止。

通过这种方式,玩家可以玩无限数量的游戏,而且您不需要复制游戏代码。示例(了解结构的外观):

// start with "yes" in order to enter the game loop initially
String again = "yes";

while(again.equals("yes")) {
    answer = generator.nextInt(101);
    System.out.println("Lets play a game. Guess the number(0-100): ");
    guess = scan.nextInt();

    while (guess != answer){
        System.out.println("Wrong guess.");
        if (guess > answer){
            System.out.println("Your guess was higher than the answer. Guess again: ");
        }
        else{
            System.out.println("Your guess was lower than the answer. Guess again: ");
        }
        guess = scan.nextInt();
    }

    System.out.println("You got it! The number was " + answer);
    // ask them if they want to play again. only "yes" will start another game
    System.out.println("Do you want to play again (yes/no)?");
    again = scan.nextLine();
}