java 随机数

Java生成随机数
[url]http://www.kirun.co.uk/java/answers/33.php[/url]
Random Numbers

The method you need to use isMath.Random();. This produces a random number from 0 to 1. To make this useful, you need to multiply by the range, and add the lowest number.

int thing = (int)(Math.random()*5);This produces a whole random number from 0 to 4
int thing = (int)(Math.random()*10+1);This produces a whole random number from 1 to 10
double thing = (Math.random()*5+1);This produces a real random number from 1 to 5

Random numbers aren't actually random, but are generated by complicated maths.

If you need a random sequence that is the same every time the program is run, then the Random class is more useful.

static Random bob = new Random(); Creates a new Random() object.
bob.setSeed(12345); Sets a seed, of type long ***check long*** + coding
System.out.println("The next random number is :" + bob.nextDouble());
System.out.println("The one after that is :" + bob.nextDouble());


NOTE: The Java section is mostly in maintenence mode. I don't have time to work on it right now. Errors will be corrected if pointed out, but they are not actively being searched for. Newer site features, like alternate stylesheets, may cause problems with these pages.
Java中生成随机数有多种方法,以下是详细介绍: ### 使用`java.util.Random`类 这是最常用的一种生成随机数的方式,需要借助`java.util.Random`类来产生一个随机数发生器。其构造函数有两个:`Random()`和`Random(long seed)`。`Random()`是以当前时间为默认种子,`Random(long seed)`是以指定的种子值进行。种子是产生随机数的第一次使用值,机制是通过一个函数,将这个种子的值转化为随机数空间中的某一个点上,并且产生的随机数均匀的散布在空间中,以后产生的随机数都与前一个随机数有关。产生随机数发生器之后,借助不同的语句产生不同类型的数。 #### 生成0到99之间的随机整数示例代码 ```java import java.util.Random; public class RandomIntegerExample { public static void main(String[] args) { Random random = new Random(); int n = random.nextInt(100); // 生成0到99之间的随机整数 System.out.println("随机整数: " + n); } } ``` #### 获取指定范围(如5 - 10之间)的随机数示例代码 ```java import java.util.Random; public class random { public static void main(String[] args) { Random rand = new Random(); System.out.println(rand.nextInt(6) + 5); } } ``` ### 使用`Math.random()`方法 `Math.random()`方法返回的数值是`[0.0, 1.0)`的`double`型数值,由于`double`类数的精度很高,可以在一定程度下看做随机数,借助`(int)`来进行类型转换就可以得到整数随机数。示例代码如下: ```java int r = (int) (Math.random() * 100); // 生成0到99之间的随机整数 System.out.println(r); ``` ### 使用`System.currentTimeMillis()` `System.currentTimeMillis()`返回当前时间的毫秒数,可利用它来生成随机数。示例代码如下: ```java long randomNum = System.currentTimeMillis(); int k = (int) (randomNum % 100); System.out.println(k); ``` ### 关于继承`java.util.Random`类的生成器 有一种生成器继承了`java.util.Random`类,但只有一种调用方法——通过`nextInt`生成随机数,且该方法只提供无参和单个参数两种版本,其他任何调用都将直接调用`java.util.Random`方法 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值