Another possibility to implement:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
class Main {
private static Scanner scanner;
public static void main(String[] args) {
System.out.println("Digite o tamanho da lista");
scanner = new Scanner(System.in);
int quantidade = scanner.nextInt();
List<Integer> listadistintos = new ArrayList<Integer>();
int sorteio;
do {
boolean adicionarLista = true;
sorteio = (int) (Math.random() * 100); //ajustar valores aqui
for (int i : listadistintos){
if (i == sorteio) {
adicionarLista = false;
break;
}
}
if (adicionarLista) { listadistintos.add(sorteio); }
} while (listadistintos.size() < quantidade);
//System.out.println("Lista de números distintos");
//for (int x : listadistintos) {
// System.out.println(x);
//}
}
}
One thing to be careful about is that depending on the parameters you pass, you can generate an infinite loop.
Ex:
If I change the parameters to Math.random() * 5)
And I want to generate a list with 6 positions. The output condition of the loop do
will never be achieved.
Because there is only the possibility of being drawn 5 different numbers.
0 , 1 , 2, 3, 4
https://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates
– user60252