如何在 Java 中使用 Random 生成兩個獨立的輸出


要生成兩個獨立的輸出,首先建立一個新的 Random 物件,−

private static final Random r = new Random();

現在我們宣告一個值−

int val = 5;

從該值迴圈到 100 並生成 1 到 100 之間的隨機數−

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

同樣地,用不同的條件生成一個不同的輸出。

示例

 現場演示

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++;
      }
   }
}

輸出

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

更新於:30-7 月-2019

154 位觀看者

開啟您的 職業

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.