ErezBerez
ErezBerez

Reputation: 131

Java random number

Beginner question here: I tried creating a random number using this code

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

however, i kept receiving 0 as the answer when printing to screen

only after putting parenthesis like so

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

did the number show properly. Can anyone explain the logical reason for this that I missed?

Upvotes: 3

Views: 642

Answers (5)

Stefano
Stefano

Reputation: 3235

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

is equivalent to

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

Considering that Math.random() return a number from 0<=N<1, if you try to cast it you will always get 0, that multiply by 10 is still 0

int rand = ((int) Math.random()); -- ALWAYS --> ZERO

0*N ---- ALWAYS ---> ZERO

Upvotes: 0

user4668606
user4668606

Reputation:

The other answers already explained the issue with your code, so I won't cover this topic here anymore.

This is just a note on the generation of random-numbers:
The recommended way of generating random-numbers in java isn't Math.random() , but via the java.util.Random class (http://docs.oracle.com/javase/7/docs/api/java/util/Random.html).

To generate a random-number like in the above example, you can use this code:

Random rnd = new Random();
int i = rnd.nextInt(10);

, which will produce the same result as your code.

Upvotes: 2

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

The code

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

is equivalent to

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

So the value of Math.random() is converted to an int. Because that value is between 0 and 1 (1 excluded) it is converted always to zero.

So

(int) Math.random()*10 -->  ((int) Math.random()) * 10 --> 0 * 10 --> 0

Upvotes: 3

Ga&#235;l J
Ga&#235;l J

Reputation: 15275

When you write int rand = (int) Math.random()*10, you're actually writing:

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

Therefore you get 0 because the random number is between 0 and 1, and casting it to an int makes it equals to 0.

Upvotes: 5

Eran
Eran

Reputation: 394086

Math.random() returns a double number between 0 and 1 exclusive, which means (int)Math.random() will always be 0 (since Math.random() < 1). In order to perform the multiplication before the cast to int, you must use parentheses as you did.

Upvotes: 3

Related Questions