[英]How to generate random unique numbers on java
I'm new to Java and im trying to randomize non-repeating numbers for a game. 我是Java的新手,我正尝试将游戏的非重复数字随机化。 My code generates unique random numbers from 1 to 75 only if i do not add a break statement, (which i have to do to only get one number at the time).
仅当我不添加break语句时,我的代码才会生成从1到75的唯一随机数(我必须这样做才能同时获得一个数字)。 What do I do?
我该怎么办? edit -(i was wondering if the reason it kept resetting is because i called on the method multiple times? im not too sure how to fix that)
编辑-(我想知道它是否保持重置的原因是因为我多次调用该方法吗?我不太确定如何解决该问题)
public static void genNumber() {
Random random = new Random();
int num;
String u;
String letter = "";
HashSet<Integer> used = new HashSet<>(75);
for (int i = 1; i <= 75; i++){
ball.add(i);
}
while(used.size() > 0) {
num = 1 + random.nextInt(75);
if (used.contains(num)){
used.remove(new Integer(num));
u = Integer.toString(num);
System.out.print(u + "\n");
break;
}
if (!used.contains(num)){
continue;
}
}
The numbers are unique and random but i only want one number at the time (without repeating) not all 75 at once. 这些数字是唯一且随机的,但我一次只想要一个数字(不重复),而不是一次全部75。
Perhaps shuffle the list each time you want a new random sequence, like a deck of cards. 也许每当您想要一个新的随机序列(如一副纸牌)时,就对列表进行洗牌。 Each element is guaranteed to be unique.
每个元素都保证是唯一的。
List<Integer> balls = new ArrayList<>();
for (int i = 1; i <= 75; ++i) {
balls.add(i);
}
for (;;) {
// Shuffle the list every 75 draws:
Collections.shuffle(balls);
System.out.println(Arrays.toString(balls.toArray()));
// Consume the sequence
for (Integer ball : balls) {
take(ball);
}
}
I would make a 75 element array of boolean values and set all the values to true. 我将创建一个由75个元素组成的布尔值数组,并将所有值设置为true。 Make a method that generates one random number and update your boolean array at that value to false.
创建一个生成一个随机数的方法,并将该布尔数组的值更新为false。 Each time you generate a number check your array to see if that value is set to true.
每次生成数字时,请检查数组以查看该值是否设置为true。 Then you can keep generating numbers one at a time and not have to worry about getting repeats.
然后,您可以一次生成一个数字,而不必担心重复。 You can have a while loop that asks the user to input yes or no and if they answer no it won't call your method and set your while loop condition to false.
您可以有一个while循环,要求用户输入yes或no,如果用户回答no,则不会调用您的方法并将while循环条件设置为false。 and if they answer yes it does call the method and keeps looping.
如果他们回答“是”,则它会调用方法并保持循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.