Java Reference
In-Depth Information
public class Lottery extends JApplet {
// Generate NUMBER_COUNT random selections from the VALUES array
private static int[] getNumbers() {
// Store for the numbers to be returned
int[] numbers = new int[NUMBER_COUNT];
int candidate = 0;
// Stores a candidate
selection
for(int i = 0 ; i < NUMBER_COUNT ; ++i) { // Loop to find the
selections
search:
// Loop to find a new selection different from any found so far
while(true) {
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...
}
Directory "Lottery 1"
The
getNumbers()
method returns a reference to an array of values of type
int
that represent the se-
lections — which must all be different, of course. You start the process by creating an array to hold the
selections, and a variable,
candidate
, to hold a potential selection for the
values
array. You generate a
new selection for each iteration of the outer loop. The process for finding an acceptable selection is quite
simple. In the indefinite
while
loop with the label
search
, you choose a random value from the
values
array using the 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
statement goes to the next
iteration of the indefinite
while
loop. This continues until a selection is found that is different from the
others. In this way you ensure that you end up with a set of selections that are all different.
Let's implement the
init()
method and the
createGUI()
method for the
Lottery
class next, as these
set up the
Selection
buttons and the rest of the applet.