JAVA中如何隨機生成確定範圍中的隨機數
阿新 • • 發佈:2019-01-25
Java中生成確定範圍中的隨機數,有兩種方法:
(1)使用util包下面的Random類,Random類中有一個nextInt()方法,用於生成隨機的整數。nextInt(int n),引數n表示0<=隨機數<n。所以在實際應用中,應該靈活使用。
下面例子,隨機生成50個[10, 50]之間的隨機數。
- import java.util.Random;
- publicclass RandomTest
- {
- publicstaticvoid main(String[] args)
- {
-
Random random = new
- for(int i = 0; i < 50; i++)
- {
- System.out.println(random.nextInt(41) + 10);
- }
- }
- }
(2)使用lang包下,Math類的random()方法。不過此方法的返回型別是double型別的,同時生成的隨機值的取值範圍是[0.0, 1.0),所以在實際應用中,也應注意其靈活性。
- publicclass RandomTest
- {
-
publicstaticvoid main(String[] args)
- {
- for(int i = 0; i < 50; i++)
- {
- System.out.println((int)(Math.random() * 41 + 10));
- }
- }
- }