# A little help with my lottery numbers please

• 04-03-2013, 10:54 PM
shane-01
A little help with my lottery numbers please
Hi everyone

I just want to get a bit of help with this lottery number program I'm trying to make.
I've not been playing with java that long, only 6 days into java in 21 days by sams the sixth edition
and I thourght I'd challenge myself so If there is any obvious errors I've made let me know.

this is my code so far

import java.util.Random;
import java.util.Arrays;

public class Lottery {

public static void main(String[] args) {
int[] todaysNumbers = new int[6];
Random random = new Random();
System.out.println("Todays numbers are ");

//for (int i = 0; i < todaysNumbers.length; i++) {
// todaysNumbers[i] = random.nextInt(49) + 1;
//}

todaysNumbers[0] = random.nextInt(49) + 1; // first number
for (int i = 1; i < todaysNumbers.length; i++) { // loop for next 5 numbers
todaysNumbers[i] = random.nextInt(49) + 1;
for (int k = 1; k < i; k++) { // loop to test the latest number against the rest
while (todaysNumbers[k] == todaysNumbers[i]) { // should generate new number if there is a duplicate ???
todaysNumbers[k] = random.nextInt(49) + 1;
}
}
}
Arrays.sort(todaysNumbers); // sorts todaysNumbers[] in to numerical order

for (int j = 0; j < todaysNumbers.length; j++) {
System.out.print(todaysNumbers[j] + " ");
}
}
}

for some reason I'm still getting the odd duplicated number
nut I'm not too sure why
• 04-03-2013, 11:31 PM
sehudson
Re: A little help with my lottery numbers please
I would approach this by:

-Creating an ArrayList of Integers(let's call it generatedNums?)
-Go through this loop until generatedNums contains 6 Integers
---Generate a random number(call it r?)
---If generatedNums does not contain r, add r to generatedNums.
• 04-04-2013, 02:02 AM
Junky
Re: A little help with my lottery numbers please
You can simplify the above advice by using a Set which does not allow duplicates.

Alternatively, create and fill a List with all numbers. Shuffle the List. Read 6 numbers from the front of the List.

But the use of some of these concepts are beyond a 6 day Java user.