[英]Selecting a random color in java
I have an iPhone version of my application which is using a bit of code for setting up colors. 我的应用程序有一个iPhone版本,该版本使用一些代码来设置颜色。
((rand() % 176) * 80) / 256.0f
I am new to objective c
so I can't figure out how this is working. 我是objective c
新手,所以我不知道这是如何工作的。 I want to make exact copy of this for Android in Java
. 我想用Java
为Android制作此副本。
In Java we usually use Random()
. 在Java中,我们通常使用Random()
。 How am i suppose to implement this above function using Random r = Random();
我应该如何使用Random r = Random();
来实现上述功能Random r = Random();
In Android, I'd first initialize a variable rand = new Random()
. 在Android中,我首先要初始化一个变量rand = new Random()
。 Then I would write your expression as: 然后,我将您的表达式写为:
rand.nextInt(176) / 3.2f
(Note that 80 / 256.0 == 1 / 3.2
.) I would only assign a value to rand
once and reuse the same Random
object each time I needed a new color. (请注意80 / 256.0 == 1 / 3.2
。)我只给rand
分配一个值,并且每次需要新颜色时都重复使用相同的Random
对象。
After a little back-of-the-envelope work, it seems that your original code is just a fancy way of computing a random float value uniformly distributed between 0 and 55.0f. 经过少量的工作后,看来您的原始代码只是一种计算均匀分布在0到55.0f之间的随机浮点值的理想方法。 Thus, a much simpler way of doing the same thing would be: 因此,做同一件事的简单得多的方法是:
rand.nextFloat(55)
The only disadvantage of this is that it doesn't resemble the original code very closely (although it will behave the same). 这样做的唯一缺点是,它与原始代码不太相似(尽管它的行为相同)。
Equivalent one-liner in Java would be: Java中的等效单行代码为:
((new Random().nextInt() % 176) * 80) / 256.0f;
More about the random class on the JavaDoc 有关JavaDoc上的随机类的更多信息
Obviously you should not create a new instance of Random
each time. 显然,您不应该每次都创建一个新的Random
实例。
Random r = new Random();
// call r.nextInt() each time you need a new random integer
double color = ((r.nextInt() % 176) * 80) / 256.0f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.