Guess the number - Java Program

Q. Write a java class NumGuesserGame in which a computer generates a random number from 1-10. User has to identify the number generated by computer. The computer will respond as "Correct Guess" if guess is correct otherwise respond as "not correct".

Answer:

An instance of Random class is used to generate a stream of pseudorandom numbers. In this example 1-10 random are generated and user can guess the generated number.

NumGuesserGame.java

import java.util.Random;
import java.util.Scanner;
public class NumGuesserGame
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        Random random = new Random();
        int from = 1;
        int to = 10;
        int randomNumber = random.nextInt(to - from + 1) + from;
        int guessedNumber = 0;

        System.out.printf("The number is between %d and %d.\n", from, to);

        do
        {
            System.out.print("Guess what the number is: ");
            guessedNumber = scan.nextInt();
            if (guessedNumber > randomNumber)
                System.out.println("Incorrect guess!!");
            else if (guessedNumber < randomNumber)
                System.out.println("Incorrect guess!!");
            else
                System.out.println("Correct guess!!\n\n\n");
        } while (guessedNumber != randomNumber);
    }
}


Output:

number guess