Kako v Javi ustvarim naključna cela števila v določenem območju?
Kako ustvarim naključno vrednost int
v določenem območju?
Poskusil sem z naslednjimi načini, vendar ti ne delujejo:
Poskus 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Kus 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
V Javi 1.7 ali novejši je standardni način za to naslednji:
Glej ustrezni dokument JavaDoc. Prednost tega pristopa je, da ni treba izrecno inicializirati instance java.util.Random, kar je lahko ob neustrezni uporabi vir zmede in napak.
Vendar pa nasprotno ni načina za izrecno nastavitev semena, zato je lahko težko reproducirati rezultate v primerih, ko je to koristno, na primer pri testiranju ali shranjevanju stanja igre in podobno. V teh primerih se lahko uporabi tehnika pred izdajo Jave 1.7, ki je prikazana spodaj.
Pred Javo 1.7 je bil standardni način izvedbe naslednji:
Glej ustrezni dokument JavaDoc. V praksi je razred java.util.Random pogosto boljši od java.lang.Math.random().
Zlasti ni treba na novo izumljati kolesa za generiranje naključnih celih števil, če je v standardni knjižnici na voljo enostaven API za izvedbo te naloge.
Uporaba: