美文网首页
【练习】生成1-20的随机数,不重复

【练习】生成1-20的随机数,不重复

作者: 御都 | 来源:发表于2019-05-19 20:16 被阅读0次

要求:获取10个1-20之间的随机数要求不能重复

import java.util.ArrayList;
import java.util.Random;
/*获取10个1-20之间的随机数要求不能重复
 *1 创建一个集合存放生成的随机数
 *2 使用while(集合中不存在该元素)就生成一个元素,将元素加入到集合中
 *3 重复2 10次
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(getNum(10));
    }
    public static ArrayList<Integer> getNum(int m){
        ArrayList<Integer> list = new ArrayList<Integer>();
        int n = (int)(Math.random()*20 + 1);
        for(int i=0;i<m;i++){
            while(list.contains(n)){
                n = (int)(Math.random()*20 + 1);
            }
            list.add(n);
        }
        //方法二
        int count = 0;
        Random r = new Random();
        while(count<m){
            int i = r.nextInt(20) +1;
            if(!list.contains(i)){
                list.add(i);
                count++;
            }
        }
        return list;
    }
    
}

相关文章

网友评论

      本文标题:【练习】生成1-20的随机数,不重复

      本文链接:https://www.haomeiwen.com/subject/praqzqtx.html