粗略的看了其他樓的答案,雖然大部分都能實現,但沒有精妙的地方,而好的程序在於精妙,這樣才能執行的更快速。我看了我6L的,說實話,他的程序還不錯,只是他忽略了一點,他的循環只有一次,而如果數字有重復的情況下,SET就很難存到 10 個數字,不信的話,樓主可以吧他程序里的 100 改成 20 試試,問題就很明顯了。
以下是我隨手寫的,相比6L,顯得好多了。
public class Test2 {
public static void main(String[] args){
Random ran = new Random();
Set <Integer> set = new HashSet<Integer>();
while(set.size()==10?false:true){
int num = ran.nextInt(100)+1;
set.add(num);
}
Iterator<Integer> it = set.iterator();
int count = 0;
while(it.hasNext()){
System.out.println("第"+ ++count +"個隨機數 =="+it.next());
}
}
}