1. 程式人生 > >JAVA中如何隨機生成確定範圍中的隨機數

JAVA中如何隨機生成確定範圍中的隨機數

Java中生成確定範圍中的隨機數,有兩種方法:

(1)使用util包下面的Random類,Random類中有一個nextInt()方法,用於生成隨機的整數。nextInt(int n),引數n表示0<=隨機數<n。所以在實際應用中,應該靈活使用。

          下面例子,隨機生成50個[10, 50]之間的隨機數。

  1. import java.util.Random;  
  2. publicclass RandomTest  
  3. {  
  4.     publicstaticvoid main(String[] args)  
  5.     {  
  6.         Random random = new
     Random();  
  7.         for(int i = 0; i < 50; i++)  
  8.         {  
  9.             System.out.println(random.nextInt(41) + 10);  
  10.         }  
  11.     }  
  12. }  

(2)使用lang包下,Math類的random()方法。不過此方法的返回型別是double型別的,同時生成的隨機值的取值範圍是[0.0, 1.0),所以在實際應用中,也應注意其靈活性。

  1. publicclass RandomTest  
  2. {  
  3.     publicstaticvoid main(String[] args)  
  4.     {  
  5.         for(int i = 0; i < 50; i++)  
  6.         {  
  7.             System.out.println((int)(Math.random() * 41 + 10));  
  8.         }  
  9.     }  
  10. }