简体   繁体   中英

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!

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

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:

One of the easiest ways to randomly generate 0 or 1 in Java:

   (int) (Math.random()+0.5);
    or
   (int) (Math.random()*2);
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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM