加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 创建唯一的随机数

发布时间:2020-12-15 04:53:32 所属栏目:Java 来源:网络整理
导读:我创建了以下方法,以便创建唯一的随机数. (此唯一值属于树的节点): static Random rand = new Random();public static ArrayListNode go(int n) { ArrayListNode list = new ArrayListNode(); ArrayListInteger numList = new ArrayListInteger(); // TODO
我创建了以下方法,以便创建唯一的随机数. (此唯一值属于树的节点):

static Random rand = new Random();
public static ArrayList<Node> go(int n) {
    ArrayList<Node> list = new ArrayList<Node>();
    ArrayList<Integer> numList = new ArrayList<Integer>();
    // TODO Auto-generated method stub
    for(int i = 1; i<=5; i++)
    {
        int number = rand.nextInt(10)+1;
        if(list.size()>0 && !check(list,number))
        {
            i--;
            continue;
        }
        numList.add(number);
        Node node = new Node();
        node.data = number;
        list.add(node);
    }
     int w  = 0;
    for (Node d : list) {
        System.out.println(w+": "+d.data);
        w++;
    }
    return list;

}
  private static boolean check(ArrayList<Node> list,int num) {
    // TODO Auto-generated method stub
    boolean b = false;
    /*if(list.size()==0)
        return true;
    */
    for (Node node : list) {
        if(node.data == num)
            b = false;
        else
            b = true;
    }
    return b;
}

但它不会创建唯一的数字,我的列表中仍然存在重复数字.喜欢 :

0: 10
1: 1 
2: 10 
3: 5 
4: 6

解决方法

问题是如果找到重复的数字,你不会在check函数内停止for循环.循环继续,b可以变回true.

你应该做的是例如:

private static boolean check(ArrayList<Node> list,int num) {
    for (Node node : list) {
        if(node.data == num)
            return false;
    }
    return true;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读