Number Guessing Game in Java
Ramya K

Ramya K @ramya_kamalasekaran

About: Having 2.5 years of Experience in Software field. After a career gap planning to start my career again

Joined:
Jan 26, 2025

Number Guessing Game in Java

Publish Date: May 20
1 0

Guessing the number game:
`package com.first;

import java.util.Random;
import java.util.Scanner;

public class Number_Guessing_Game {

public static void main(String[] args) {
    int real_number=(int) Math.round(Math.random()*100);
    Scanner scanner=new Scanner(System.in);
    int no_of_attempts=10;
    while(no_of_attempts>0) {
        System.out.println("Enter the number from 1 to 100 to guess");
        int guess_number=scanner.nextInt();
        if(real_number==guess_number) {
            System.out.println("Hooray you found the number");
        break;
        }
        else if(real_number>guess_number) 
            System.out.println("Think higher number");

        else
            System.out.println("Think Lower number");
        no_of_attempts++;
        }


    if(no_of_attempts==10)
        System.out.println("You are Exhausted, the correct number is "+real_number);
}
Enter fullscreen mode Exit fullscreen mode

}
`
output:
Enter the number from 1 to 100 to guess
56
Think higher number
Enter the number from 1 to 100 to guess
89
Think Lower number
Enter the number from 1 to 100 to guess
78
Hooray you found the number

Explanation:
Here i used Math function random() to get the random number. Then i rounded the value using Math function round(). Stored the number in realnumber.
Here i have given only 10 attempts to find the number. If the number is found print found message else help the user to find the number using lower or greater number.
If the user didn't find until 10 attempts print the real number.

Comments 0 total

    Add comment