Random numbers

My question is: How to draw a number from 0 to 4 in Java (android)? How to use the random function?

+3
source share
4 answers

The following will do what you need.

Random r = new Random();
int randomInt = r.nextInt(5);

If you do this in a loop, make sure you initialize Randomout of loop.

Random r = new Random();
for(int i = 0;i < someThing; i++) {
    System.out.println(r.nextInt(5));
}

See the documentation for the class Random: http://download.oracle.com/javase/6/docs/api/java/util/Random.html

+8
source

Be careful, as you should not create a new random object every time you want to get a new number. This line should be run once at application startup:

Random r = new Random();

, :

int x = r.nextInt(5);
+2
System.out.println(""+(int) (Math.random()*5.0));

, , Math.random(), .

: 0 n, (0 , n ), :

(int) (Math.random()*n);

m m + n, (m , m + n ), :

m + (int) (Math.random()*n);
+2

, Attantion - :

Random r = new Random();

, ( , phanamona).

, - Java : Java: Can (new Random()). nextInt (5) ? : Java random , ?

:

static Random sRandomGen = new Random();

nextInt , . , .

int rnd = sRandomGen.nextInt(numofmatches - 1);

.

+2

Source: https://habr.com/ru/post/1779251/


All Articles