Java Reference
In-Depth Information
Once we have the intersection, we can ask for its size to see how many of the
player's numbers were winning numbers; we can then calculate the appropriate cash
prize amount for the player on the basis of that number. (Our version starts with a
$100 prize and doubles that figure for each winning number.)
Here is a complete implementation of the lottery program. We've created a few
static methods for structure and added a few constants to represent the number of
numbers, maximum number, and lotto prize amounts:
1 // Plays a lottery game with the user, reading
2 // the user's numbers and printing how many matched.
3
4 import java.util.*;
5
6 public class Lottery {
7 public static final int NUMBERS = 6;
8 public static final int MAX_NUMBER = 40;
9 public static final int PRIZE = 100;
10
11 public static void main(String[] args) {
12 // get winning number and ticket sets
13 Set<Integer> winning = createWinningNumbers();
14 Set<Integer> ticket = getTicket();
15 System.out.println();
16
17 // keep only winning numbers from user's ticket
18 Set<Integer> matches = new TreeSet<Integer>(ticket);
19 matches.retainAll(winning);
20
21 // print results
22 System.out.println("Your ticket was: " + ticket);
23 System.out.println("Winning numbers: " + winning);
24 if (matches.size() > 0) {
25 double prize = 100 * Math.pow(2, matches.size());
26 System.out.println("Matched numbers: " + matches);
27 System.out.printf("Your prize is $%.2f\n", prize);
28 }
29 }
30
31 // generates a set of the winning lotto numbers
32 public static Set<Integer> createWinningNumbers() {
33 Set<Integer> winning = new TreeSet<Integer>();
34 Random r = new Random();
35 while (winning.size() < NUMBERS) {
36 int number = r.nextInt(MAX_NUMBER) + 1;
Search WWH ::




Custom Search