Christopher Baldwin
Christopher Baldwin

Reputation: 347

math.random, only generating a 0?

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!

Upvotes: 6

Views: 23242

Answers (4)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

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);

Upvotes: 23

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

public static double random()

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

 int croll =1+(int)Math.random()*3-1;

eg

 int croll =1+0*-1; 


System.out.println(croll); // will print always 0 

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213263

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:

Upvotes: 6

Suresh Atta
Suresh Atta

Reputation: 121998

All our mates explained you reasons of unexpected output you got.

Assuming you want generate a random croll

Consider Random for resolution

    Random rand= new Random();
    double croll = 1 + rand.nextInt() * 3 - 1;
    System.out.println(croll);

Upvotes: 0

Related Questions