Math.random question (no it is not a random question..I think)

How come there must be () around int and math.random and why do there have to be () after math.random in

int targetNumber = (int) (math.random() * 10);

thanks in advance

also why are there double "int"s

Message was edited by:

sys5

[334 byte] By [sys5a] at [2007-11-27 5:10:12]
# 1

> How come there must be () around int and math.random

> and why do there have to be () after math.random in

>

> int targetNumber = (int) (math.random() *

> 10);

>

Because the random method returns a double so you want to cast the result to an int. If you leave out the brackets around the * 10 part then only the value returned from random method is cast to int. by including the * 10 inside the bracket you multiply the value returned from the random number by 10 before casting to int. There maybe some requirement of where the loss of precision occurs. Actually, if you cast the value returned to an int before multiplication then the only values you will get are either 0 or 1 then multiply by ten gives 0 or 10.

> also why are there double "int"s

>

WHAT? I've never heard of any such thing.

Ack! On further thinking the only value you will get is zero as random method returns a value 0.0 to less than 1.0. So casting any value to int will give 0.

Message was edited by:

flounder

floundera at 2007-7-12 10:30:12 > top of Java-index,Java Essentials,New To Java...
# 2

I think what he means is when you declare the variable as type INT and when you cast INT onto the (math.random * 10).

Variables have to be a declared datatype. Since math.random returns a double, you have to cast the returned value from math.random as INT in order for your code to compile and run correctly.

sampson5455a at 2007-7-12 10:30:12 > top of Java-index,Java Essentials,New To Java...
# 3

> why do there have to be () after math.random

Because random is a method of the Math class. Some classes allow you to access member variables - like the "out" of System.out - but most of the time you will be calling methods, and these will have () after them. If the method in question takes no arguments then the () will be empty.int targetNumber = (int) (math.random() * 10);

^ random is a method

^ we want an int not a double

^^ we are casting the whole expression

pbrockway2a at 2007-7-12 10:30:12 > top of Java-index,Java Essentials,New To Java...