新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
簡單介紹產生Java隨機數(shù)的兩種方法
本文總結了產生Java隨機數(shù)的兩種方法:

1.在j2se中使用Math.random()(產生0-1之間的double)方法:
如
- public void numCreate(){
- int array[] = new int[10];
- for(int i=0;i<10;i++){
- array[i]=(int)(Math.random()*100);
- for(int j=0;j
- if(array[i] == array[j]){
- i--;
- break;
- }
- }
- }
- for(int t=0;t
- System.out.println(array[t]);
- }
- }
2.使用Random對象產生隨機數(shù),他可以產生隨機的整數(shù)和浮點數(shù)。利用Random實例的next..()方法。一般情況選擇不帶種子的方式生成隨機數(shù)。如
- public void numCreate(){
- int array[] = new int[10];
- for(int i=0;i<10;i++){
- Random r = new Random();
- array[i] = r.nextInt(100);
- for(int j=0;j
- if(array[i] == array[j]){
- i--;
- break;
- }
- }
- }
- for(int t=0;t
- System.out.println(array[t]);
- }
- }
其中nextInt方法中的參數(shù)可以設置產生數(shù)字的范圍。在0(包括)和指定值(不包括)之間 。
這兩個生成Java隨機數(shù)的方法,你學會了么?
【編輯推薦】
- Java隨機數(shù)總結(第二部分)
- Java隨機數(shù)總結(***部分)
- 走進Java 7中的模塊系統(tǒng)
- Java產生不重復隨機數(shù)方法
- Java基礎教程
網站標題:簡單介紹產生Java隨機數(shù)的兩種方法
URL網址:http://www.5511xx.com/article/cosphsd.html


咨詢
建站咨詢
