简体   繁体   中英

Java - How to generate random number of a specific range using a seed?

I am new to java and trying to figure out how to generate a random number from 0.000-1.000 using a seed which will be inputted by the user. If someone can show some example code it would help a lot. Thanks in advance.

You can try:

System.out.println("Type a number");
Scanner sc = new Scanner(System.in);
int seed = sc.nextInt();
Random random = new Random(seed);
double randomNumber = random.nextDouble();
System.out.printrln("The random number is: " + randomNumber);

The Java Random class allows for seeds. You can instantiate it with a seed and also change the seed on the fly.

Random rangen = new Random(123456789);
int result = rangen.nextFloat(); // Returns double between 0.0 and 1.0;
String seedStr = "This String can be used for a seed by using the Hash Code";
rangen.setSeed(seedStr.hashCode());

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM