java產生隨機數的方法_java

來源:互聯網
上載者:User

本文執行個體講述了java產生隨機數的方法。分享給大家供大家參考。具體實現方法如下:

package com.tool.code; import java.util.Random; public class RandomNum {  private static char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',  '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',  'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',  'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',  'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',  'z', '0', '1' }; //最後又重複兩個0和1,因為需要湊足數組長度為64 private static Random random = new Random(); //產生指定長度的隨機字串 public static String createRandomString(int length) {  if (length > 0) {   int index = 0;   char[] temp = new char[length];   int num = random.nextInt();   for (int i = 0; i < length % 5; i++) {    temp[index++] = ch[num & 63];   //取後面六位,記得對應的二進位是以補碼形式存在的。    num >>= 6;//63的二進位為:111111    // 為什麼要右移6位?因為數組裡面一共有64個有效字元。   //為什麼要除5取餘?因為一個int型要用4個位元組表示,也就是32位。  }   for (int i = 0; i < length / 5; i++) {    num = random.nextInt();    for (int j = 0; j < 5; j++) {     temp[index++] = ch[num & 63];     num >>= 6;    }   }   return new String(temp, 0, length);  } else if (length == 0) {   return "";  } else {   throw new IllegalArgumentException();  } } //根據指定個數,測試隨機字串函數的重複率 public static double rateOfRepeat(int number){  int repeat=0;  String[] str=new String[number];  for(int i=0;i<number;i++){//產生指定個數的字串   str[i]=RandomNum.createRandomString(10);  }  for(int i=0;i<number;i++){//尋找是否有相同的字串   for(int j=i+1;j<number-1;j++){    if(str[i].equals(str[j]))     repeat++;   }  }  return ((double)repeat)/number; } public static void main(String[] args) {  System.out.println(RandomNum.createRandomString(16)+"-"+RandomNum.createRandomString(16));  double rate=RandomNum.rateOfRepeat(10000);//測試10000次的重複率  System.out.println("重複率:"+rate); }}

控制台運行效果如下:

希望本文所述對大家的java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.