Java Reference
In-Depth Information
int
j =
2
+
'a'
;
// (int)'a' is 97
System.out.println(
"j is "
+ j);
// j is 99
System.out.println(j +
" is the Unicode for character "
+ (
char
)j);
// j is the Unicode for character c
System.out.println(
"Chapter "
+
'2'
);
display
i is 101
j is 99
99 is the Unicode for character c
Chapter 2
Note
The Unicodes for lowercase letters are consecutive integers starting from the Unicode for
'a'
, then for
'b'
,
'c'
, . . . , and
'z'
. The same is true for the uppercase letters. Fur-
thermore, the Unicode for
'a'
is greater than the Unicode for
'A'
, so
'a' - 'A'
is
the same as
'b' - 'B'
. For a lowercase letter
ch,
its corresponding uppercase letter is
(char)('A' + (ch - 'a'))
.
2.17.4 Case Study: Counting Monetary Units
Suppose you want to develop a program that changes a given amount of money into smaller
monetary units. The program lets the user enter an amount as a
double
value representing a
total in dollars and cents, and outputs a report listing the monetary equivalent in the maximum
number of dollars, quarters, dimes, nickels, and pennies, in this order, to result in the
minimum number of coins, as shown in the sample run.
Here are the steps in developing the program:
1. Prompt the user to enter the amount as a decimal number, such as
11.56
.
2. Convert the amount (e.g.,
11.56
) into cents (
1156
).
3. Divide the cents by
100
to find the number of dollars. Obtain the remaining cents using
the cents remainder
100
.
4. Divide the remaining cents by
25
to find the number of quarters. Obtain the remaining
cents using the remaining cents remainder
25
.
5. Divide the remaining cents by
10
to find the number of dimes. Obtain the remaining
cents using the remaining cents remainder
10
.
6. Divide the remaining cents by
5
to find the number of nickels. Obtain the remaining
cents using the remaining cents remainder
5
.
7. The remaining cents are the pennies.
8. Display the result.
The complete program is given in Listing 2.10.
L
ISTING
2.10
ComputeChange.java
1
import
java.util.Scanner;
2
3
public class
ComputeChange {
4
public static void
main(String[] args) {
5
// Create a Scanner
6 Scanner input =
new
Scanner(System.in);
7
8
// Receive the amount
9 System.out.print(
import class