Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

math.random, only generating a 0?

Tags:

java

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!

like image 235
Christopher Baldwin Avatar asked Oct 03 '13 14:10

Christopher Baldwin


People also ask

Can math random generate 0?

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.

Can math random produce 1?

The Math. random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

Does nextInt include 0?

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.


2 Answers

You are using Math.random() which states

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.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);
like image 98
Sotirios Delimanolis Avatar answered Oct 27 '22 02:10

Sotirios Delimanolis


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:

  • Math.random() versus Random.nextInt(int)
like image 6
Rohit Jain Avatar answered Oct 27 '22 03:10

Rohit Jain