Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random number in a range using Math.random() [duplicate]

Tags:

java

random

math

I'm not too familiar with Math.random(); and I don't know what to do for the conditions that I want. I want to produce a random integer between 0 and 52 so far this is what I have set up.

    public class Tester{
    public static void main(String args[]){
        int size=52;
        while(size>0){
            int rando=(int)Math.random()*size;
            size--;
            System.out.println(rando);
        }
    }
}

My code prints out all 0's until the condition of the while loop is met. I wanted to know how I would produce a random integer between 0 and 52. I understand that Math.random(); produces a double and I think theres a problem with the type casting. Thanks.

like image 714
Tariq Al-Attrash Avatar asked Feb 18 '16 17:02

Tariq Al-Attrash


4 Answers

You only cast Math.random(). Its a value between 0 and 1 (excluding 1). If you cast this it's zero anyway.

Cast the whole expression: (int)(Math.random()*size);

BTW: Your interval is only from 0 to 51 (because of the excluding 1.

Use (int)(Math.random()*(size+1));, if you want 0...52 as your interval.

like image 199
osanger Avatar answered Oct 19 '22 09:10

osanger


The cast takes precedence over the multiplication. Since Math.random() returns a double in the range [0.0..1.0), it will always be converted to 0, and the result of multiplying that by any other int will of course be 0. You could perform the multiplication before casting - ((int)(Math.random()*size)), but really it'd be easier to use Random.nextInt(int).

like image 40
Mureinik Avatar answered Oct 19 '22 09:10

Mureinik


Math.random() returns a pseudo-random number with a domain of [0 , 1).

In the line:

int rando=(int)Math.random()*size;

this value is cast as an int and then multiplied by size. To fix the problem with only printing zeros you need to add parentheses.

int rando = (int) (Math.random()*size);

This will only give you numbers in the domain [0, 51) To fix this:

int rando = (int) (Math.random()* (size + 1);
like image 29
star2wars3 Avatar answered Oct 19 '22 10:10

star2wars3


Necessary to use the Math class?

a simpler way to find this number would using the Random class

Example:

Random randomNumber = new Random ();
System.out.println(randomNumber.nextInt(53));

See also:

Math.random() versus Random.nextInt(int)

like image 43
Douglas Ribeiro Avatar answered Oct 19 '22 10:10

Douglas Ribeiro