Math.random() returns a random float in the range [0.0,1.0) - this means that the result can be any value from 0 to, but not including 1.0.
Your code
double rAsFloat = 1 * (2 + Math.random( ) );
will accept this number in the range [0.0,1.0]; adding 2 to it gives you a number in the range [2.0.3.0]; multiplying it by 1, nothing is useful; then when you truncate it to an integer, the result is always 2.
To get integers from this kind of random functions, you need to figure out how many integers you could return, and then multiply a random number by them. If you want to get the answer "0 or 1", your range will consist of two different integers, so multiply Math.random() by 2:
double rAsFloat = 2 * Math.random();
This gives you a random number in the range [0.0,2.0), which can be 0 or 1 when you trim the integer with (int) . If instead you need something that returns 1 or 2, for example, you would just add 1 to it:
double rAsFloat = 1 + 2 * Math.random();
I think you already realized that the Random class gives you what you want a lot easier. I decided to explain all this, because someday you can work on an outdated system in some old language, where you really need to work with a random value [0.0,1.0). (OK, maybe this is not very likely, but who knows.)
source share