How can I generate two separate outputs using Random in Java


To generate two separate outputs, at first create a new Random object −

private static final Random r = new Random();

Now, let us declare a value −

int val = 5;

Loop from the value till 100 and generate random numbers between 1 to 100 −

while (val<= 100) {
   System.out.printf("%-4d", r.nextInt(20) * 1);
   if (val % 5 == 0) {
      System.out.println();
   }
   val++;
}

In the same way, generate a different output with different conditions.

Example

 Live Demo

import java.util.Random;
public class Demo {
   private static final Random r = new Random();
   public static void main(String[] args) {
      int val = 5;
      while (val<= 100) {
         System.out.printf("%-4d", r.nextInt(20) * 1);
         if (val % 5 == 0) {
            System.out.println();
         }
         val++;
      }
      System.out.println();
      val = 20;
      while (val<= 100) {
         System.out.printf("%-4d", r.nextInt(10 * (20)));
         if (val % 5 == 0) {
            System.out.println();
         }
         val++;
      }
   }
}

Output

1
18 2 1 16 0
8 15 1 6 0
19 13 10 14 16
13 5 16 5 14
16 13 14 1 2
14 11 11 12 9
18 11 16 2 3
4 17 8 8 19
7 0 15 14 11
10 12 4 17 13
19 17 1 12 8
1 14 6 3 6
10 10 7 3 4
18 19 12 7 6
3 11 2 6 1
4 18 9 11 2
16 16 3 19 18
18 14 2 18 2
13 7 8 8 2
72
72 53 2 60 19
187 57 138 16 124
20 67 0 94 3
51 127 84 146 126
86 125 29 68 30
124 61 88 127 11
87 139 30 156 12
39 133 117 11 179
124 199 1 91 117
44 43 160 181 74
171 187 167 192 174
49 106 172 118 44
19 95 155 199 69
54 84 27 4 30
51 122 122 122 47
63 193 76 115 56

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements