I found answers on how to generate random numbers but nowhere how to generate all the numbers in the range without duplication in Java. Please share if you have a solution. Below is what I did but it simply generates randomly the numbers. I need to print out all numbers in the range without duplication!
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");
}
}
}
Aucun commentaire:
Enregistrer un commentaire