创建唯一的随机数

编程入门 行业动态 更新时间:2024-10-27 04:28:35
本文介绍了创建唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了以下方法以创建唯一的随机数。 (此唯一值属于树的节点):

I have created the following method so as to create unique random numbers . (This unique values belong to the nodes of a tree):

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

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

But it doesn’t create unique numbers and there are still duplicates in my list. Like :

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

推荐答案

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

The problem is that you don't stop the for loop inside the check function if it finds a duplicated number. The loop continues and b can change back to true.

你应该做的是例如:

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

更多推荐

创建唯一的随机数

本文发布于:2023-10-28 23:07:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!