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();
    }
}

      

+3


source to share


4 answers


You should use double for int after multiplying by 10:

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

      



Otherwise, you will always get 0 (since Math.random()<1.0

and therefore (int)Math.random()

always 0).

+5


source


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)

+3


source


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.

+1


source


You shouldn't use Math.random () to generate random integers as it will generate random floats (i.e. decimal numbers)

You should do something similar to this

Random myRandom = new Random();
int randomInt = myRandom.nextInt(10);

      

-1


source







All Articles