<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);
}
}
}