Generating Random Numbers
Hi,
I thought this would be the best place to start as I am effectively new to the java language.
I started writing code to generate numbers for the UK lottery. I thought I'd try extend it to make the program generate X random numbers between a min and a max value.
I seem to be getting incorrect random numbers when running this, if I use min 1 and max 49 as the arguments it appears ok.
If I use min 300 and max 400 I get numbers like 578 and 666.
I've spent quite a bit of time researching the Random.nextInt method but would like to know if ive misinterpreted the way that this method works.
Thanks.
PS please feel free to add any comments re code layout or other tips. This is all a great learning experience for me.
import java.util.Random;
import java.util.Arrays;
publicclass ArrayTestApp{
/**
* @param args
*/
publicstaticvoid main(String[] args){
// TODO Auto-generated method stub
ArrayTester test1 =new ArrayTester(1, 49);
test1.getNumbers();
ArrayTest test2 =new ArrayTest(300, 400);
test2.getNumbers();
}
}
class ArrayTester
{
privateint numbers[] =newint [6];
private Random generator =new Random();
public ArrayTester(int min,int max)
{
setNumbers(min, max);
}
publicvoid setNumbers(int min,int max)
{
System.out.printf("Min = %d, Max = %d\n", min, max);
int i = 0;
while (i < numbers.length)//control is less than array length
{
//generate a new number between min and max
int num = min + generator.nextInt(max);
System.out.println("Generated number = " + num);
// call method haveNumber to see if we already have a generated number
// if we do not then add our number to the array
if (!haveNumber(numbers, num))
{
numbers[i] = num;
++i;
}
}//end while
}//end method setNumbers
// add - returns true if the number is already in the array
// or false if the number does not exist
publicboolean haveNumber(int list[],int val)
{
for (int count = 0; count < list.length; count++)
{
if (list[count] == val)
{
returntrue;
}
}
returnfalse;
}
// print out the array of numbers
publicvoid getNumbers()
{
//sort the array
Arrays.sort(numbers);
//print out each number
for (int count = 0; count < numbers.length; count ++)
System.out.printf("Number%d = %d\n" , count+1, numbers[count]);
}// end getNumbers
}// end class ArrayTest

