4位或6位隨機數生成(用於短信驗證碼)


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
* 生成四位和六位的隨機數字
*/
public class RandomUtils {

private static final Random random = new Random();

private static final DecimalFormat fourdf = new DecimalFormat("0000");

private static final DecimalFormat sixdf = new DecimalFormat("000000");

public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}

public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}

/**
* 給定數組,抽取n個數據
* @param list
* @param n
* @return
*/
public static ArrayList getRandom(List list, int n) {

Random random = new Random();

HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

// 生成隨機數字並存入HashMap
for (int i = 0; i < list.size(); i++) {

int number = random.nextInt(100) + 1;

hashMap.put(number, i);
}

// 從HashMap導入數組
Object[] robjs = hashMap.values().toArray();

ArrayList r = new ArrayList();

// 遍歷數組並打印數據
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM