Java中提供了两种主要的获取随机数的方法,分别是Random随机数类和Math.random()函数,其中Random随机数类更为常用。
Java中生成随机数的方法代码范例和输出结果如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| package Random;
import java.util.Random;
public class RandomTest {
public static void main(String[] args) { Random rd = new Random(); System.out.println(rd.nextInt()); System.out.println(rd.nextInt(100)); System.out.println(rd.nextLong()); System.out.println(rd.nextDouble()); System.out.println("=========================");
System.out.println(Math.round(Math.random()*10)); System.out.println("=========================");
rd.ints(); int[] arr = rd.ints(10).toArray(); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } System.out.println("=========================");
arr = rd.ints(5, 10, 100).toArray(); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
System.out.println("=========================");
arr = rd.ints(10).limit(5).toArray(); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| 1404320356 53 -8492628924417241038 0.06849198818168623 ========================= 1 ========================= -1312517856 -509940637 2134173514 -1742855070 447151405 -1519546383 -512164412 -1127120168 -978804043 -1470191102 ========================= 69 39 41 98 17 ========================= 1744076186 498618148 -584035397 546922796 1704853629
|