I'm trying to create a random number generator with java that and output 3 numbers from 1-8 using seeds from user input, such as a user inputs 1 as a seed it sets out a set of 3 numbers, then sets out another 3 numbers, if the user inputs another seed such as 4 then it will give a different set of numbers?
I know how to use scnr.nextInt();
for the user input for the seed, but how do I use it for the seed and number generator?
In java random numbers can be produced using class Random.For example:
Random randomNumbers=new Random();
int random=randomNumbers.nextInt();
This generates a random number from –2,147,483,648 to +2,147,483,647. In the above code, no seed value is given. So the program uses the current system time in milliseconds as the seed value.Thus the above statement is equivalent to:
Random randomNumbers=new Random(System.currentTimeMillis());
A specific seed always generates a identical set of random numbers.Since the time keeps changing, the sequence generated using the time of day as a seed always gives a unique set of random values.
Now how to generate random numbers within a certain range? The statement:
Random randomNumbers=new Random(2);
int random=randomNumbers.nextInt(8);
generates a random number from 0 to 7 using the seed value 2 which we can off course make an user to input.The value 8 is called scaling factor. But in most of the cases we have to shift these values in order to get he desired output.So the random numbers generated above should be shifted by 1. Thus we write a expression:
int randomNum=1+randomNumbers.nextInt(8);
Now it generates random numbers in the range 1 to 8.
In order to generate 3 random numbers in a sequence you can use a loop.
for(int i=0;i<3;i++){
int random=1+randomNumbers.nextInt(8);
System.out.println(random);
}