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

1.在j2se中使用Math.random()(產(chǎn)生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對象產(chǎn)生隨機數(shù),他可以產(chǎn)生隨機的整數(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è)置產(chǎn)生數(shù)字的范圍。在0(包括)和指定值(不包括)之間 。
這兩個生成Java隨機數(shù)的方法,你學(xué)會了么?
【編輯推薦】
- Java隨機數(shù)總結(jié)(第二部分)
- Java隨機數(shù)總結(jié)(***部分)
- 走進Java 7中的模塊系統(tǒng)
- Java產(chǎn)生不重復(fù)隨機數(shù)方法
- Java基礎(chǔ)教程
當(dāng)前題目:簡單介紹產(chǎn)生Java隨機數(shù)的兩種方法
標(biāo)題URL:http://m.5511xx.com/article/cosphsd.html


咨詢
建站咨詢
