How to use the clock as a random generator seed in Java

2 Answers

0 votes
import java.util.Random;

public class RandomSeedExample {
    public static void main(String[] args) {
        // Use the current time in milliseconds as the seed
        long seed = System.currentTimeMillis();
        
        // Create a new Random object with the seed
        Random random = new Random(seed);
        
        // Generate a positive random integer
        int randomInt = Math.abs(random.nextInt()); // Ensures non-negative output
        
        // Alternatively, specify an upper limit to guarantee a positive value
        int boundedRandomInt = random.nextInt(Integer.MAX_VALUE); // Random from 0 to MAX_VALUE
        
        // Generate a random double
        double randomDouble = random.nextDouble();
        
        // Print the random numbers
        System.out.println("Positive Random Integer (Math.abs method): " + randomInt);
        System.out.println("Positive Random Integer (Bounded method): " + boundedRandomInt);
        System.out.println("Random Double: " + randomDouble);
    }
}



/*
run:

Positive Random Integer (Math.abs method): 267054746
Positive Random Integer (Bounded method): 121779822
Random Double: 0.577271447726375

*/

 



answered May 8 by avibootz
0 votes
import java.util.Random;

class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Random rand = new Random(System.currentTimeMillis());
		
		System.out.println(rand.nextInt());
	}
}



/*
run:

1095432807

*/

 



answered May 8 by avibootz
...