Java Program to generate random number with restrictions

Java 8Object Oriented ProgrammingProgramming

To generate random number with resctrictions, here we are taking an example of a phone number from India with the country code 91.

First, we have set the first 2 numbers i.e. the country code. The variables are declared for each digit. We have also fixed the first digit of the number as 9 after country code 91:

Random num = new Random();
int num0, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10, num11;
num0 = 9;
num1 = 1;
num2 = 9;

Now, for rest of the numbers, use the nextInt() of the Random. The parameter consists of the bound set for random numbers:

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

Example

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
raja
Published on 24-Apr-2019 12:18:56
Advertisements