Java Reference
In-Depth Information
if
ch
is
'B'
, and so on. When two characters perform a numerical operation, the characters'
Unicodes are used in the computation.
The program invokes the
Character.isDigit(ch)
method to check if
ch
is between
'0'
and
'9'
(line 22). If so, the corresponding decimal digit is the same as
ch
(lines 23-24).
If
ch
is not between
'A'
and
'F'
nor a digit character, the program displays an error message
(line 27).
4.5.3 Case Study: Revising the Lottery Program Using Strings
The lottery program in ListingĀ 3.8, Lottery.java, generates a random two-digit number, prompts
the user to enter a two-digit number, and determines whether the user wins according to the
following rule:
1. If the user input matches the lottery number in the exact order, the award is $10,000.
2. If all the digits in the user input match all the 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.
The program in ListingĀ 3.8 uses an integer to store the number. ListingĀ 4.5 gives a new
program that generates a random two-digit string instead of a number and receives the user
input as a string instead of a number.
L
ISTING
4.5
LotteryUsingStrings.java
1
import
java.util.Scanner;
2
3
public class
LotteryUsingStrings {
4
public static void
main(String[] args) {
5
// Generate a lottery as a two-digit string
6 String lottery =
""
+ (
int
)(Math.random() *
10
)
7 + (
int
)(Math.random() *
10
);
8
9
// Prompt the user to enter a guess
10 Scanner input =
new
Scanner(System.in);
11 System.out.print(
"Enter your lottery pick (two digits): "
);
12 String guess = input.nextLine();
13
14
generate a lottery
enter a guess
// Get digits from lottery
15
char
lotteryDigit1 = lottery.charAt(
0
);
16
char
lotteryDigit2 = lottery.charAt(
1
);
17
18
// Get digits from guess
19
char
guessDigit1 = guess.charAt(
0
);
20
char
guessDigit2 = guess.charAt(
1
);
21
22 System.out.println(
"The lottery number is "
+ lottery);
23
24
// Check the guess
25
if
(guess.equals(lottery))
26 System.out.println(
"Exact match: you win $10,000"
);
27
else if
(guessDigit2 == lotteryDigit1
28 && guessDigit1 == lotteryDigit2)
29 System.out.println(
"Match all digits: you win $3,000"
);
30
else if
(guessDigit1 == lotteryDigit1
31 || guessDigit1 == lotteryDigit2
32 || guessDigit2 == lotteryDigit1
33 || guessDigit2 == lotteryDigit2)
34 System.out.println(
"Match one digit: you win $1,000"
);
exact match?
match all digits?
match one digit?
Search WWH ::
Custom Search