Java Reference
In-Depth Information
public class Lottery extends JApplet {
// Generate numberCount random selections from the values array
static int[] getNumbers() {
int[] numbers = new int[numberCount]; // Store for the numbers to be returned
int candidate = 0; // Stores a candidate selection
for(int i = 0; i < numberCount; i++) { // Loop to find the selections
search:
// Loop to find a new selection different from any found so far
for(;;) {
candidate = values[choice.nextInt(values.length)];
for(int j = 0 ; j<i ; j++) // Check against existing selections
if(candidate==numbers[j]) // If it is the same
continue search; // get another random selection
numbers[i] = candidate; // Store the selection in numbers array
break; // and go to find the next
}
}
return numbers; // Return the selections
}
// Plus the rest of the class definition...
}
The
getNumbers()
method returns a reference to an
int
array containing the selections - which
must all be different, of course. We start the process by creating an array to hold the selections, and a
variable,
candidate
to hold a potential selection from the
values
array. We generate a new selection
for each iteration of the outer
for
loop. The process is quite simple. In the indefinite
for
loop with the
label,
search
, we choose a random value from the
values
array using our random number generator,
and then check its value against any selections already stored in the
numbers
array. If it is the same as
any of them, the labeled
continue
will go to the next iteration of the indefinite
for
loop. This will
continue until a selection is found that is different from the others. In this way we ensure that we end up
with a set of selections that are all different.
Let's implement the
init()
method for the
Lottery
class next, as this sets up the
Selection
buttons and the rest of the applet.
Try It Out - Setting Up the Lucky Number Buttons
In the class outline we identified two tasks for the
init()
method. The first was setting up the lucky
number buttons to be contained in the
luckyNumbers
array.
Here's the code to do that:
// Initialize the applet
public void init() {
// Set up the selection buttons
Container content = getContentPane();
content.setLayout(new GridLayout(0,1)); // Set the layout for the applet
// Set up the panel to hold the lucky number buttons