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.
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.
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)
.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With