How to generate a random integer using the math.random class
I am having problems with the method RandInt()
as it does not return a random integer. The result should be int ranged 0-9
and should use the math.random class. This is my code below:
public class RandNumGenerator {
public static int RandInt() {
int n = (int) Math.random() * 10;
return n;
}
public static void main(String[] args) {
RandInt();
}
}
source to share
Casting has a higher priority than*
, so the code
(int) Math.random() * 10;
coincides with
((int) Math.random()) * 10;
and since it Math.random()
returns values ββin the range [0; 1)
(1 - excluded) when pressedint
(int) Math.random()
will produce 0
multiplied by 10 will also return 0
.
you can use
(int) (Math.random() * 10)
or easier to read and maintain Random#nextInt(max)
to create a range [0; max)
( max
-exclusive)
source to share
You need to put parentheses around the multiplication
int n = (int) (Math.random() * 10);
what's happening
int n = ((int) Math.random()) * 10;
as Math.random()
always greater than or equal to 0 and less than 1, converting it to an integer will always be zero. Multiplying it by 10, nothing happens.
source to share