我找到了关于如何生成随机数的答案,但没有找到如何在 Java 中不重复地生成范围内所有数字的答案。如果您有解决方案,请分享。下面是我所做的,但它只是随机生成数字。我需要不重复地打印出范围内的所有数字!
package com.company;
import java.util.*;
public class RandomizeNumbers {
public static void main(String[] args) {
//Create Scanner
Scanner userInput = new Scanner(System.in);
//Ask for numbers N and M
System.out.println("Please enter two numbers and the program will randomize the numbers between them. " +
"The first number N must be bigger or equal to the second number M");
System.out.println("Please enter the first number N");
int n = userInput.nextInt();
System.out.println("Please enter the second number M");
int m = userInput.nextInt();
Random randomGenerator = new Random();
int difference = n - m;
//Randomize the numbers
if (m<=n){
for(int i = 0; i<= difference; i++ ) {
int randomInt = randomGenerator.nextInt(n - m + 1) + m;
System.out.println(randomInt);
}
}
else{
System.out.println("Please enter M less or equal to N");
}
}
}
最佳答案
您可能需要生成随机排列,请参阅此链接 How to generate a random permutation in Java?
关于java - 如何在 Java 中不重复地在两个给定整数之间随机生成所有数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341643/