# Java 中的 HiLo 猜猜游戏

> 原文： [https://howtodoinjava.com/puzzles/hilo-guessing-game-in-java/](https://howtodoinjava.com/puzzles/hilo-guessing-game-in-java/)

你们中的许多人在您的童年时代一定玩过 HiLo 游戏。 即使不完全相同，游戏也可能与此类似。 很好玩吧？ 那如果我们现在成年了怎么办？ 让我们以自己的方式再次玩这个游戏。 让我们为此构建一个 Java 程序，然后开始玩这个精彩的游戏 HiLo。

## 用 Java 编写 HiLo 游戏

在下面的程序中，我尝试用 Java 语言模拟 HiLo 游戏。 我为此版本的游戏设定了两个简单的规则：

1.  最多猜 6 次密码。
2.  机密数字是 1 到 100（含）之间的整数。

每次您猜到一个低于机密号码的数字（只有 JRE 知道）时，都会打印“ LO”。 同样，如果您猜到一个比机密数字高的数字，则会打印“ HI”。 您必须调整下一个猜测，以便能够在六次尝试中猜测正确的数字。

```java
package hilo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class HiLo {

    private Random generator;
    private int generatedNumber;
    private int numberOfAttempts;
    BufferedReader reader = null;

    public HiLo() {
        generator = new Random();
        reader = new BufferedReader(new InputStreamReader(System.in));
    }

    public void start() throws IOException {

        boolean wantToPlay = false;
        boolean firstTime = true;

        do {
            System.out.println();
            System.out.println();
            System.out.println("Want to play the game of Hi and Lo??");
            if (wantToPlay = prompt()) {
                generatedNumber = generateSecretNumber();
                numberOfAttempts = 0;
                if (firstTime) {
                    describeRules();
                    firstTime = false;
                }
                playGame();
            }

        } while (wantToPlay);

        System.out.println();
        System.out.println("Thanks for playing the game. Hope you loved it !!");
        reader.close();
    }

    private void describeRules() {
        System.out.println();
        System.out.println("Only 2 Rules:");
        System.out.println("1) Guess the secret number in maximum 6 tries.");
        System.out.println("2) The secret number is an integer between 1 and 100, inclusive :-)");
        System.out.println();
        System.out.println();
    }

    private int generateSecretNumber() {
        return (generator.nextInt(100) + 1);
    }

    private void playGame() throws IOException {

        while (numberOfAttempts < 6) {

            int guess = getNextGuess();

            if (guess > generatedNumber) {
                System.out.println("HI");
            } else if (guess < generatedNumber) {
                System.out.println("LO");
            } else {
                System.out.println("Brave Soul, You guessed the right number!! Congratulations !!");
                return;
            }
            numberOfAttempts++;
        }

        System.out.println("Sorry, you didn't guess the right number in six attempts. In other two words, YOU LOST !!!!");
        System.out.println("The secret number was " + generatedNumber);

    }

    private boolean prompt() {

        boolean answer = false;

        try {

            boolean inputOk = false;
            while (!inputOk) {
                System.out.print("Y / N : ");
                String input = reader.readLine();
                if (input.equalsIgnoreCase("y")) {
                    inputOk = true;
                    answer = true;
                } else if (input.equalsIgnoreCase("n")) {
                    inputOk = true;
                    answer = false;
                } else {
                    System.out.println("Ohh come on. Even Mr. Bean knows where are 'y' and 'n' in the keyboard?? Please try again:");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        return answer;
    }

    private int getNextGuess() throws IOException {

        boolean inputOk = false;
        int number = 0;
        String input = null;
        while (!inputOk) {
            try {

                System.out.print("Please guess the secret number: ");
                input = reader.readLine();
                number = Integer.parseInt(input);
                if (number >= 1 && number <= 100) {
                    inputOk = true;
                } else {
                    System.out.println("Really? You didn't read the rules boy. Your number is not between 1 and 100 (" + number + ").");
                }
            } catch (NumberFormatException e) {
                System.out.println("Invalid input (" + input + ")");
            }
        }

        return number;
    }
}

```

## 玩 HiLo 游戏

现在，游戏已准备就绪。 播放吧。

```java
package hilo;

import java.io.IOException;

public class PlayGame
{
   public static void main(String[] args)
   {
      HiLo hiLo = new HiLo();
      try {
          hiLo.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output:

Want to play the game of Hi and Lo??
Y / N : y

Only 2 Rules:
1) Guess the secret number in maximum 6 tries.
2) The secret number is an integer between 1 and 100, inclusive.

Please guess the secret number: 40
LO
Please guess the secret number: 60
LO
Please guess the secret number: 80
HI
Please guess the secret number: 70
LO
Please guess the secret number: 75
LO
Please guess the secret number: 77
HI
Sorry, you didn't guess the right number in six attempts. In other two words, YOU LOST !!!!
The secret number was 76

```

希望您喜欢这个游戏。

**祝您学习愉快！**