I am new in JAVA and I think I have searched all the questions without finding one similar to my question.
I want to generate random numbers that would give back 4 fixed numbers using Math.random(). The numbers that I want to get are: 0, 90. 180 and 270. In other words, I want to 4 numbers with a minimum value of 0 and maximum value of 270 and an increment of 90.
int rand = ((int)(Math.random()*4)) * 90;
Let's break that down. Start with Math.random()
, returning a random decimal in the range [0,1). (Anything between 0 and 0.999999999..., loosely.)
Math.random()*4 //Gives a random decimal between 0 and 4 (excluding 4)
Next, let's truncate the decimal.
(int)(Math.random()*4) //Truncates the decimal, resulting in a random int: 0, 1, 2, or 3
Finally, we'll multiiply by 90.
int rand = ((int)(Math.random()*4)) * 90; //0*90=0, 1*90=90, 2*90=180, or 3*90=270
You'd better create a java.util.Random
object and reuse it:
Random r = new java.util.Random();
...
int x = r.nextInt(4)*90;
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.