黑馬程式設計師-JAVA基礎面試-獲取10個1-20 的隨機數,要求獲取的隨機數不能相同!
阿新 • • 發佈:2019-02-03
<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); } } }