Random Number Generator Always gives 0
Why does it give me a 0 when my range is specifically 1~56?
Code:
Code Java:
//**********random()***************
public static int random(int a, int b)
{
return((int)((b - a + 1)*Math.random() + a));
}
//**********superLottoNumbers()*********
public static int[] superLottoNumbers()
{
int numZ[] = new int[6];
for(int h = 0; h <=4; h++)
{
numZ[h] = random(1,47);
}
Arrays.sort(numZ);
numZ[5] = random(1,27);
return(numZ);
}
//**********megaMillionNumbers()*********
public static int[] megaMillionNumbers()
{
int numZ[] = new int[6];
for(int i = 0; i <= 4; i++)
{
numZ[i] = random(1,56);
}
Arrays.sort(numZ);
numZ[5] = random(1,46);
return(numZ);
}
public static void main(String args[])
{
if(commandLine1(args[0]) == false) System.out.println("Not a valid type of Lottery");
//if(commandLine2(args[1]) == false) System.out.println("Not a valid number of tickets");
if(args[0].equalsIgnoreCase("sl"))
{
int num[] = new int[6];
num = superLottoNumbers();
for(int h: num) System.out.print(h+" ");
}
if(args[0].equalsIgnoreCase("mm"))
{
int num[] = new int[6];
num = megaMillionNumbers();
for(int i: num) System.out.print(i+" ");
}
}
}
HELP ASAP. THanks
Re: Random Number Generator Always gives 0
When you compile your code, you will notice it's the first number which is always 0.
All the others are random and within the correct range.
It's deceiving though as the Arrays.sort(numZ); makes it the first one.
So in reality, it looks like the last number is always printed as 0.
With this in mind, it looks as though the last value of the array isn't being populated.
Which leads us to the part of the code which populates the array.
Take a look at:
Code Java:
for (int i = 0; i <= 4; i++) {
numZ[i] = random(1, 56);
}
The problem is your for loops. See if you can figure out what it is :)
In future, my advice is to go back through your code and break it down into smaller parts. Get each part working correctly and make sure you understand what is happening before moving on.
Re: Random Number Generator Always gives 0
Why don't you just:
Code :
int number = 1+new Random().nextInt(56);
Seems alot simpler, doesn't it?