Number Guessing Game in Java

number-guessing-game-in-java

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

}
`
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.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
specifying-a-force-measurement-and-material-testing-system-to-suit-your-application

Specifying a Force Measurement and Material Testing System to Suit Your Application

Next Post
uniface-for-beginners:-how-to-properly-define-numeric-parameters

Uniface for Beginners: How to Properly Define Numeric Parameters

Related Posts