Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Number Guessing Game in Java
Next article icon

Number Guessing Game in Java

Last Updated : 09 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A number-guessing game in Java is a simple program where the computer randomly selects a number, and the user has to guess it within a limited number of attempts. The program provides feedback on whether the guessed number is too high or too low, guiding the user toward the correct answer.

This project is an excellent way for beginners to practice loops, conditionals, user input handling, and random number generation in Java.

Rules of the Game:

  • If the guessed number is bigger than the actual number, the program will respond with the message that the guessed number is higher than the actual number.
  • If the guessed number is smaller than the actual number, the program will respond with the message that the guessed number is lower than the actual number.
  • If the guessed number is equal to the actual number or if the K trials are exhausted, the program will end with a suitable message.

Implementation Details

  • The program generates a random number between a predefined range (e.g., 1 to 100).
  • The user has limited attempts (K tries) to guess the number.
  • At each guess, the program provides a hint:
    • If the guessed number is higher, it tells the user to guess lower.
    • If the guessed number is lower, it tells the user to guess higher.
  • If the user guesses correctly, they win.
  • If all attempts are exhausted, the game reveals the correct number.

Approach:

To implement the game, we need to follow the steps listed below:

  • Generate a random number using the Math.random() method.
  • Take user input using Scanner.
  • Compare the guess with the random number and provide feedback.
  • Limit the number of attempts using a loop.
  • Handle edge cases (e.g., invalid inputs).

Implementation:

The below Java program demonstrates the number-guessing game:

Java
// Java Program to demonstrates the Number guessing game import java.util.Scanner;  public class Geeks {          public static void guessingNumberGame()     {         Scanner sc = new Scanner(System.in);          // Generate a random number between 1 and 100         int number = 1 + (int)(100 * Math.random());                  // Number of attempts         int K = 5;          System.out.println(             "A number is chosen between 1 and 100.");         System.out.println(             "You have " + K             + " attempts to guess the correct number.");          // Loop for K attempts         for (int i = 0; i < K; i++) {             System.out.print("Enter your guess: ");             int guess = sc.nextInt();              // Check conditions             if (guess == number) {                 System.out.println(                     " Congratulations! You guessed the correct number.");                 sc.close();                                  // Exit function if guessed correctly                 return;             }             else if (guess < number) {                 System.out.println(                     " The number is greater than " + guess);             }             else {                 System.out.println(                     " The number is less than " + guess);             }         }          // If the user runs out of attempts         System.out.println(             "You've exhausted all attempts. The correct number was: "             + number);         sc.close();     }      public static void main(String[] args)     {         guessingNumberGame();     } } 

Output:

Output


Note: You can also use Random class from java.util instead of Math.random() to generate random numbers in Java.

Random random = new Random();

int number = random.nextInt(100) + 1;


Number Guessing Game with Unlimited Rounds and Score Tracking

Approach:

  • After Exhausting K attempts, the user is given another chance to continue the game.
  • The game tracks the score (number of attempts taken to guess correctly).
  • The game continues until the user guesses the correct number.

Implementation:

The below Java program demonstrates the number-guessing game with Unlimited Rounds and Score Tracking.

Java
// Number guessing game with // Unlimited Rounds and Score Tracking import java.util.Scanner;  public class Geeks {     public static void guessingNumberGame()     {         Scanner sc = new Scanner(System.in);          // Generate a random number between 1 and 100         int number = 1 + (int)(100 * Math.random());                  // Track the number of attempts         int attempts = 0;                   // Maximum attempts per round         int K = 5;          boolean guessedCorrectly = false;          System.out.println(             "A number is chosen between 1 and 100.");         System.out.println(             "You have " + K             + " attempts per round to guess the correct number.");          while (!guessedCorrectly) {                          // Give the user K attempts per round             for (int i = 0; i < K; i++) {                 System.out.print("Enter your guess: ");                 int guess = sc.nextInt();                 attempts++; // Increment attempt count                  if (guess == number) {                     System.out.println(                         "Congratulations! You guessed the correct number in "                         + attempts + " attempts.");                     guessedCorrectly = true;                     break;                 }                 else if (guess < number) {                     System.out.println(                         "The number is greater than "                         + guess);                 }                 else {                     System.out.println(                         "The number is less than " + guess);                 }             }              if (!guessedCorrectly) {                                  // Ask the user if they want to continue                 // after exhausting K attempts                 System.out.println("You have used all " + K                                    + " attempts.");                 System.out.print(                     "Do you want to continue guessing? (yes/no): ");                 String response = sc.next();                  if (!response.equalsIgnoreCase("yes")) {                     System.out.println(                         "Game Over! The correct number was: "                         + number);                     break;                 }             }         }          sc.close();     }      public static void main(String[] args)     {         guessingNumberGame();     } } 

Output:

Output

Next Article
Number Guessing Game in Java

S

SAKSHIKULSHRESHTHA
Improve
Article Tags :
  • Mathematical
  • Java Programs
  • DSA
Practice Tags :
  • Mathematical

Similar Reads

    Hangman Game in Java
    Hangman is a popular word guessing game where the player endeavors to construct a lost word by speculating one letter at a time. After a certain number of off base surmises, the game finishes and the player loses. The game also finishes when the player accurately distinguishes all the letters of the
    6 min read
    Duck Number Java
    In this article, we will look at a Duck Number in Java. We will look at its meaning and rules for a number to be Duck Number with the help of examples and write a Java program to demonstrate and verify it through our code. What is Duck Number?A Duck Number is a positive non-zero number containing at
    4 min read
    Java Program to Guess a Random Number in a Range
    Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display Too high, try again. If the user’s guess is lower than the random number, the program should display Too low, try again. The
    2 min read
    Tic-Tac-Toe Game in Java
    Tic-Tac-Toe is a classic game that two people can enjoy together. It is played on a 3x3 grid where players take turns placing their marks, X or O, in empty spots. The main goal is to get three of the same marks in a row-horizontally, vertically, or diagonally.In this article, we are going to build a
    7 min read
    Fizz Buzz Program in Java
    FizzBuzz is a game popular amongst kids that also teaches them the concept of division. In recent times it has become a popular programming question. Following is the problem statement for the FizzBuzz problem. Examples: Input: 9Output: FizzExplanation: The number is divisible by 3 only. Input: 25Ou
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences