Number guessing game in Java

Number guessing game in Java

A number guessing game is a simple guessing game where a user is supposed to guess a number between 0 and N. So let’s see a simple program of number guessing game in java.

import java.util.Scanner;
import java.util.Random;
class numguess
{
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Random r = new Random();
    System.out.println("GUESS THE NUMBER!");
    System.out.println("================== ");
    System.out.println("Enter your guess (number from 0-10): ");
    int g = sc.nextInt();
    int n = r.nextInt(11);
    System.out.println("------------------");
    if (g > 10)
      System.out.println("Invalid choice!");
    else if (n == g)
      System.out.println("Number=" + n + "\nYou win!");
    else
      System.out.println("Number=" + n + "\nYou lose!");
    System.out.println("------------------");
  }
}

Output-

number guessing output java

Explanation-

For using Random class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc. Then we pass arguments to generate numbers. So when we pass 11 as argument, the range is 0 to 10 both inclusive. Then it will compare the random generated number to user input. If it is greater than 10, it will print “Invalid input”. If the numbers match you win else you lose.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. Scanner– Scanner is a class in java.util package used for obtaining the input.
  7. Random– Random is a class in java.util package to generate random integers, floats , doubles, etc.
  8. String[] args– Used for command line argument.
  9. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.
  10. System.in is an InputStream.

Conclusion-

So this was the simple Number guessing game in java. We hope it was clear to you. If you have doubt regarding any concept or this post just mention it in the comments. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

Leave a Reply

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