How to Generate A Same Random Number Sequence in Java


In this example, let’s us see how to generate a same Random number sequence within the Random() constructor.

Source Code

package com.beginner.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;

public class SameRandomNumberSequence {

	public static void main(String[] args) {

		Random random1 = new Random(1);

		Random random2 = new Random(1);

		System.out.println("random1:");
		for (int i = 0; i <= 8; i++) {

			System.out.print(random1.nextInt(20) + " ");
			
		}

		System.out.println("nrandom2:");
		for (int i = 0; i <= 8; i++) {

			System.out.print(random2.nextInt(20) + " ");
		}

		InputStream read = System.in;
		
		BufferedReader reader2 = new BufferedReader(new InputStreamReader(read));
		try {
			System.out.println(reader2.readLine());
			
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

}

Output:

random1:
5 8 7 13 14 4 14 6 18 
random2:
5 8 7 13 14 4 14 6 18 

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments