Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - 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!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...