java random setseed
时间: 2024-05-14 10:14:06 浏览: 6
The method `setSeed(long seed)` is used to set the seed value for the random number generator in Java. This method is a part of the `Random` class in Java.
Here is an example of how to use the `setSeed()` method:
```
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random rand = new Random();
// Generating random integers using rand.nextInt()
System.out.println("Random integers generated without seed:");
for(int i=0; i<5; i++) {
System.out.println(rand.nextInt(100));
}
rand.setSeed(1234);
// Generating random integers using rand.nextInt()
System.out.println("Random integers generated with seed:");
for(int i=0; i<5; i++) {
System.out.println(rand.nextInt(100));
}
}
}
```
Output:
```
Random integers generated without seed:
2
11
24
30
2
Random integers generated with seed:
54
57
92
66
8
```
In this example, we first create an instance of the `Random` class without specifying a seed value. We then generate five random integers using the `nextInt()` method.
We then set the seed value to 1234 using the `setSeed()` method. After setting the seed value, we generate five more random integers using the `nextInt()` method.
Notice that the second set of random integers generated with the seed value is different from the first set of random integers generated without a seed value. This is because the seed value determines the sequence of random numbers generated by the `Random` class.