Java Program to generate random numbers string

Java 8Object Oriented ProgrammingProgramming

At first, create a character array −

static char num[] = { '0', '1', '2', '3', '4', '5' };

Now, let’s say you want to a string with length. Create a StringBuilder and use append() to create random numbers string out of it −

int len = 5;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
   strBuilder.append(randomNum());
}

Above, we created a randomNum() function that returns the random numbers string −

public static char randomNum() {
   return num[(int) Math.floor(Math.random() * 5)];
}

Example

 Live Demo

public class Demo {
   static char num[] = { '0', '1', '2', '3', '4', '5' };
   public static char randomNum() {
      return num[(int) Math.floor(Math.random() * 5)];
   }
   public static void main(String[] args) {
      int len = 5;
      StringBuilder strBuilder = new StringBuilder();
      for (int i = 0; i < len; i++) {
         strBuilder.append(randomNum());
      }
      System.out.println("Random numbers string = "+strBuilder.toString());
   }
}

Output

Random numbers string = 23024
raja
Published on 23-Apr-2019 09:06:55
Advertisements