<span style="font-family: 微軟雅黑; font-size: 14px; line-height: 30.8px;">------- <a href="http://www.itheima.com" target="blank">android培訓</a>、<a href="http://www.itheima.com" target="blank">java培訓</a>、期待與您交流! ----------</span>
<p>/**</p> * 需求:獲取10個1-20的隨機數,要求獲取的數據不能一樣
* 分析:使用數組不知道數組的長度,所以不嗯呢該用數組
* 使用list集合很好的解決這個問題。
* 1.創建隨機數
* 2.創建一個ArrayList集合
* 3.判斷遍歷總數小於10
* 如果是就判斷得到的隨機數是否存在集合中,存在遍歷總數++
* 如果不是遍歷輸出集合
* 代碼實現如下:
* @author Administrator
*
*/
public class Test11 {
public static void main(String[] args) {
Random r=new Random();
ArrayList<Integer> arrayList=new ArrayList<Integer>();
int count=0;
while(count<10){
int a = r.nextInt(20)+1;
if(!arrayList.contains(a)){
arrayList.add(a);
count++;
}
}
for(Integer i:arrayList){
System.out.println(i);
}
}
}