Guess the number and win the prize(game)

A simple game to guess number form 1 to 100 

import java.util.Random//Calling Random Class
import java.util.Scanner//Calling Scanner Class
public class HighLow
{
    // instance variables 
    private double x;
    public void game()
    {
        int n=1;
        int a=1;
        Random b= new Random();
        int c= b.nextInt(100);
        System.out.println("Guess the Number(1 to 100)"); //Instruction to user
        while(n<=10)
        {
            System.out.println("Guess"+n+": ");
            xnew Scanner(System.in).nextInt();
            if(c==x)
            {
                System.out.println("Brilliant!!");
                System.exit(0);
                a++; //Using Increment operator
            }
            else if(c>x)
            {
                System.out.println("Higher than "+x); //If the Random number is greater than the guessed one, this result is printed 
            }
            else if(c<x)
            {
                System.out.println("Lower than "+x); //If the Random number is lower than the guessed one, this result is printed 
            }
            n++; //Using Increment operator
        }
        if(a==1) //Condition
        {
            System.out.println("Sorry !! Try Later"); //Error message
        }
    }
    public static void main(String []args) //Main method
    {
        HighLow h=new HighLow();
        h.game();
    }
}

Random class is the built-in class inside the util package of the Java project. This function is helpful to generate a random number between any two numbers. The example of using random class is like:-


public static double getRandomNumber(){
    double x = Math.random();
    return x;
}


This program also used the Scanner class. If you have any query about Scanner class then visit this site.(https://programmerbrothers.blogspot.com/2019/04/scanner-class-in-java-scanner-is-class.html)
It use the increment operators(++) like :- a++ and n++. To gain more knowledge about Increment and the Decrement click this link.(https://programmerbrothers.blogspot.com/2019/04/increment-anddecrement-operator-as.html)

Output :-




Comments

Popular posts from this blog

Java Program to make a comparison between numbers

Java program using Scanner Class

Java program to print 'Hello World'