在 Java 中顯示小於 20 的隨機數


首先,建立一個 Random 類物件 -

Random rand = new Random();

現在,建立一個新陣列 -

int num;
int arr[] = new int[10];

迴圈並用 20 作為引數設定 Random 的 nextInt,因為你希望隨機數小於 20 -

for (int j = 0; j <= 9; j++) {
   num = 1 + rand.nextInt(20);
   arr[j] = num;
}

示例

 現場演示

import java.util.Arrays;
import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      Random rand = new Random();
      int num;
      int arr[] = new int[10];
      for (int j = 0; j<= 9; j++) {
         num = 1 + rand.nextInt(20);
         arr[j] = num;
      }
      System.out.println("Random numbers less than 20 = "+Arrays.toString(arr));
   }
}

輸出

Random numbers less than 6 = [4, 13, 14, 19, 1, 11, 17, 1, 11, 4]

更新於: 30-7 月-2019

279 次瀏覽

提升您的 職業生涯

完成課程以獲得證書

開始入門
廣告