Come posso generare numeri interi casuali entro un intervallo specifico in Java?
Come posso generare un valore int
casuale in un intervallo specifico?
Ho provato i seguenti, ma non funzionano:
Tentativo 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Tentativo 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
3359
3
In Java 1.7 o successivo, il modo standard per farlo è il seguente:
Vedere il relativo JavaDoc. Questo approccio ha il vantaggio di non dover inizializzare esplicitamente un'istanza di java.util.Random, che può essere fonte di confusione ed errore se usato in modo inappropriato.
Tuttavia, al contrario, non c'è modo di impostare esplicitamente il seme, quindi può essere difficile riprodurre i risultati in situazioni in cui ciò è utile, come i test o il salvataggio degli stati di gioco o simili. In queste situazioni, si può usare la tecnica pre-Java 1.7 mostrata qui sotto.
Prima di Java 1.7, il modo standard per farlo è il seguente:
Vedere il relativo JavaDoc. In pratica, la classe java.util.Random è spesso preferibile a java.lang.Math.random().
In particolare, non c'è bisogno di reinventare la ruota della generazione di numeri interi casuali quando c'è un'API diretta all'interno della libreria standard per eseguire il compito.
Utilizzare: