Java Reference
In-Depth Information
2.32
✓
✓
How would you write the following arithmetic expression?
Check
Point
b
2
-
b
+ 2
-
4
ac
2
a
This section presents a program that breaks a large amount of money into smaller
units.
Key
Point
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 mini-
mum number of coins.
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(
10
import class
"Enter an amount in double, for example 11.56: "
);
11
double
amount = input.nextDouble();
enter input
12
13
int
remainingAmount = (
int
)(amount *
100
);
14
15
// Find the number of one dollars
16
int
numberOfOneDollars = remainingAmount /
100
;
17 remainingAmount = remainingAmount %
100
;
18
19
dollars
// Find the number of quarters in the remaining amount
20
int
numberOfQuarters = remainingAmount /
25
;
quarters
Search WWH ::
Custom Search