使用Java怎么獲取指定個數的不同隨機數?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
1、隨機拆分一個整數
public static List<Integer> randomList(int n){
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int i = 0;
while (i < n) {
int num = rand.nextInt(n);
if (!list.contains(num)) {
list.add(num);
i++;
}
}
return list;
}2、從已知列表中隨機選取不同對象
public static List<Integer> randomList(int n,int size) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int i = 1;
while (i <= n) {
int num = rand.nextInt(size-1) + 1;
if (!list.contains(num)) {
list.add(num);
i++;
}
}
return list;
}3、把一個整數拆分成不等的幾份
public static List<Integer> randomList(int n, int m){
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int temp = m;
for(int i = 0, j; i < n-1; i++){
j = rand.nextInt(temp-1) + 1;
temp -= j;
list.add(j);
if (temp == 1){
break;
}
}
list.add(temp);
return list;
}看完上述內容,你們掌握使用Java怎么獲取指定個數的不同隨機數的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。