6

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!

Christopher Baldwin
  • 347
  • 2
  • 4
  • 15
  • 1
    http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random%28%29 Math.random returns a double between 0.0 and 1.0 , so the integer Value of it is always O. – Fabinout Oct 03 '13 at 14:52
  • 1
    see http://bmanolov.free.fr/javaoperators.php casts have higher precedence than other operations – vandale Oct 03 '13 at 14:54

4 Answers4

23

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);
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
6

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:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0
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 
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

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);
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307