Java随机NextDouble.

时间:2020-02-23 14:35:08  来源:igfitidea点击:

在本教程中,我们将看到Java随机NextDouble方法。
用于生成随机双倍。
它返回下一个伪随机组,从该随机数发生器的序列均匀分布在0.0和1.0之间。

语法

random.nextDouble()

随机是java.util.random类的对象。

返回

返回随机双倍。

例子

让我们在简单的例子的帮助下了解

package org.igi.theitroad;
 
import java.util.Random;
 
public class RandomNextDoubleMain {
 
	public static void main(String[] args) {
		Random random=new Random();
		System.out.println("Random Double: "+random.nextDouble());
		System.out.println("Random Double: "+random.nextDouble());
		System.out.println("Random Double: "+random.nextDouble());
	}
}

输出:

Random Double: 0.00885533336458566
Random Double: 0.5098436969133946
Random Double: 0.685286317774665

在范围内产生双倍

我们可以使用以下代码在范围内生成双倍。

package org.igi.theitroad;
 
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
 
public class RandomNextDoubleMain {
 
	public static void main(String[] args) {
		Random random=new Random();
 
		int rangeMin=10;
		int rangeMax=20;
		
		System.out.println("===========================================");
		System.out.println("Generating random numbers in range of 10 to 20");
		System.out.println("===========================================");
		
		for (int i = 0; i < 5; i++) {
			double randomDouble = rangeMin + (rangeMax - rangeMin) * random.nextDouble();
			System.out.println(randomDouble);
		}
		
		System.out.println("===========================================");
		System.out.println("Using ThreadLocalRandom to generate double in range of 10 to 20:");
		System.out.println("===========================================");
		
		for (int i = 0; i < 5; i++) {
			double randomNumber = ThreadLocalRandom.current().nextDouble(rangeMin, rangeMax);
			System.out.println(randomNumber);
		}
		
	}
}

输出:

Generating random numbers in range of 10 to 20
===========================================
Generating random numbers in range of 10 to 20
===========================================
17.185913130079236
10.599693774176135
19.737211130483843
19.779771283014075
11.083440540484645
===========================================
Using ThreadLocalRandom to generate double in range of 10 to 20:
===========================================
14.490580004505432
15.959990499785127
18.44256504725257
14.841549130119944
13.015851077182596