HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Puzzles / HiLo Guessing Game in Java

HiLo Guessing Game in Java

Many of you must have played HiLo game in your childhood. Game may be some sort of similar to it, if not exactly same. It was fun, right?? So what if we are adult now? Let’s play this game once again in our own way. Let’s build a java program for this and start playing this wonderful game HiLo.

Writing HiLo game in Java

In below program, I have tried to simulate the HiLo game in java language. I have set two simple rules for this version of game:

  1. Guess the secret number in maximum 6 tries.
  2. The secret number is an integer between 1 and 100, Inclusive.

Everytime you will guess a number below secret number (only JRE knows it), “LO” will be printed. Similarly, wen you guess a number higher than secret number, “HI” will be printed. You have to adjust your next guess such that you are able to guess the right number within six attempts.

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;
    }
}

Play the HiLo game

Now, the game is ready. Let’s play it.

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

Hope you enjoyed this game.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. karthick kumar

    August 20, 2014

    Nice Code….

Comments are closed on this article!

Search Tutorials

Java Puzzles

  • Interview Puzzles List
  • Dead vs Unreachable Code
  • Palindrome Number
  • Detect infinite loop in LinkedList
  • [i += j] Vs [i = i + j]
  • HiLo Guessing Game
  • Find All Distinct Duplicate Elements
  • TreeMap Put Operation
  • String With Nth Longest Length
  • Good String Vs Bad String
  • Complete String
  • Reverse String
  • Calculate Factorial
  • FizzBuzz Solution
  • Find Missing Number From Series
  • Create Instance Without New Keyword

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces