案例:產生1~20之間10個不重復的隨機數


public class Demo14 {
public static void main(String[] args){
//創建隨機數對象
Random r = new Random();
//創建集合對象
HashSet<Integer> it = new HashSet<>();
//判斷長度是否小於10,在范圍內就把隨機數添加到集合中去
while(it.size()<10){
int num = r.nextInt(20)+1;
it.add(num);
}
//遍歷集合
for (Integer x: it){
System.out.println(x);
}
}
}

輸出結果:

1
2
19
5
7
8
10
12
13
15


免責聲明!

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



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