The following code is only producing a 0 ;-;
What am I doing wrong?
public class RockPaperSci {
public static void main(String[] args) {
//Rock 1
//Paper 2
//Scissors 3
int croll =1+(int)Math.random()*3-1;
System.out.println(croll);
}
}
Edit, Another Poster suggested something that fixed it. int croll = 1 + (int) (Math.random() * 4 - 1);
Thanks, everyone!
Math. random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.
The Math. random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).
nextInt(int n) : The nextInt(int n) is used to get a random number between 0(inclusive) and the number passed in this argument(n), exclusive.
You are using Math.random()
which states
Returns a
double
value with a positive sign, greater than or equal to0.0
and less than1.0
.
You are casting the result to an int
, which returns the integer part of the value, thus 0
.
Then 1 + 0 - 1 = 0
.
Consider using java.util.Random
Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);
Math.random()
generates double values between range - [0.0, 1.0)
. And then you have typecasted the result to an int
:
(int)Math.random() // this will always be `0`
And then multiply by 3
is 0
. So, your expression is really:
1 + 0 - 1
I guess you want to put parenthesis like this:
1 + (int)(Math.random() * 3)
Having said that, you should really use Random#nextInt(int)
method if you want to generate integer values in some range. It is more efficient than using Math#random()
.
You can use it like this:
Random rand = new Random();
int croll = 1 + rand.nextInt(3);
See also:
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