Solution to 4c70: Lottery numbers
See code at solutions/code/tutorialquestions/question4c70
See sample solution in the source code archive. Lottery.java provides the preferred solution.
This uses a method, numberAlreadyChosen
, which checks whether a given int
is
already located in an array, up to a given position. The main
method consists of a while
loop. The body of this loop chooses a random integer in the range [1..49] and uses numberAlreadyChosen
to determine whether this number is unique. See how continue
is used to ensure that the while
loop does not exit until seven unique numbers have been chosen.
Observe that the numbers 7 and 49 are represented using local constants: these are fields declared static
(they exist once for the class), final
(they cannot be changed) and private
(so that they are not visible outside the class). Using constants in this way makes the code easier to read, and if we wanted to change
the number of lottery numbers, or their range, it would be very easy to do so.
LotteryLabelledContinue.java is an equivalent implementation that makes use of Java's labelled continue
construct. In this version, main
consists of a nest of two loops. The outer loop chooses a lottery number, then
uses the inner loop to check whether it is unique. If the number is not unique, continue chooseNumbers
causes
execution to immediately skip on to the next iteration of the outer loop. This may appeal to any hackers among you!