Generate Random Number with Restrictions in Java



In this article, we will learn to generate random numbers with restrictions in Java. We will be using the Java Random class from java.util package.

Random class

Random class is imported from java.util package. The instance of this class is used to generate the random numbers and provides different numbers of different types integer, double, long, float, etc.

Steps to generate random numbers with restrictions

Following are the steps to generate random numbers with restrictions ?

  • Import the Random class from the java.util package.
  • Initialize the Random object to generate random values.
  • Assign fixed values to the first few digits representing the country code.
  • Use the nextInt() method to generate restricted random values for the rest of the phone numbers.
  • Print the formatted phone number by combining all the values.

Java program to generate random numbers with restrictions

Below is the Java program to generate random numbers with restrictions ?

import java.util.Random;
public class Main {
   public static void main(String[] args) {
      Random num = new Random();
      int num0, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10, num11;
      num0 = 9;
      num1 = 1;
      num2 = 9;
      num3 = num.nextInt(9) + 10;
      num4 = num.nextInt(10);
      num5 = num.nextInt(5) + 11;
      num6 = num.nextInt(10);
      num7 = num.nextInt(3);
      num8 = num.nextInt(5);
      num9 = num.nextInt(10);
      System.out.print("Random (Country code 91 for India) = ");
      System.out.print(num0);
      System.out.print(num1);
      System.out.print("-" + num2);
      System.out.print(num3);
      System.out.print(num4);
      System.out.print(num5);
      System.out.print(num6);
      System.out.print(num7);
      System.out.print(num8);
      System.out.print(num9);
   }
}

Output

Random (Country code 91 for India) = 91-9114158010

Code Explanation

The above program uses the Random class to generate a phone number with specific restrictions. The first two digits are fixed as "91" for the country code. Some digits are randomly generated using nextInt(), where specific ranges are set for different parts of the number. For example, num3 generates a number between 10 and 18, while others like num4, num6, and num9 are between 0 and 9. Finally, all the digits are printed together to display a formatted phone number.

Updated on: 2024-10-15T10:40:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started