Java Reference
In-Depth Information
Enter a year: 2002
2002 is a leap year? false
3.12 Case Study: Lottery
The lottery program involves generating random numbers, comparing digits, and
using Boolean operators.
Key
Point
Suppose you want to develop a program to play lottery. The program randomly generates a
lottery of a two-digit number, prompts the user to enter a two-digit number, and determines
whether the user wins according to the following rules:
1. If the user input matches the lottery number in the exact order, the award is $10,000.
2. If all digits in the user input match all digits in the lottery number, the award is $3,000.
3. If one digit in the user input matches a digit in the lottery number, the award is $1,000.
Note that the digits of a two-digit number may be 0 . If a number is less than 10 , we assume
the number is preceded by a 0 to form a two-digit number. For example, number 8 is treated
as 08 and number 0 is treated as 00 in the program. Listing 3.8 gives the complete program.
L ISTING 3.8
Lottery.java
1 import java.util.Scanner;
2
3 public class Lottery {
4
public static void main(String[] args) {
5
// Generate a lottery number
6
int lottery = ( int )(Math.random() * 100 );
generate a lottery number
7
8 // Prompt the user to enter a guess
9 Scanner input = new Scanner(System.in);
10 System.out.print( "Enter your lottery pick (two digits): " );
11
int guess = input.nextInt();
enter a guess
12
13
// Get digits from lottery
14
int lotteryDigit1 = lottery / 10 ;
15
int lotteryDigit2 = lottery % 10 ;
16
17
// Get digits from guess
18
int guessDigit1 = guess / 10 ;
19
int guessDigit2 = guess % 10 ;
20
21 System.out.println( "The lottery number is " + lottery);
22
23 // Check the guess
24 if (guess == lottery)
25 System.out.println( "Exact match: you win $10,000" );
26 else if (guessDigit2 == lotteryDigit1
27 && guessDigit1 == lotteryDigit2)
28 System.out.println( "Match all digits: you win $3,000" );
29 else if (guessDigit1 == lotteryDigit1
30 || guessDigit1 == lotteryDigit2
31 || guessDigit2 == lotteryDigit1
32 || guessDigit2 == lotteryDigit2)
33 System.out.println( "Match one digit: you win $1,000" );
exact match?
match all digits?
match one digit?
 
 
 
Search WWH ::




Custom Search