- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChangeReturn.java
More file actions
Latest commit
87 lines (70 loc) · 2.49 KB
/
Copy pathChangeReturn.java
File metadata and controls
87 lines (70 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* PROJECT: Change Return
* AUTHOR: ryjo1026
* DESCRIPTION: The user enters a cost and then the amount of money given. The program will figure
* out the change and the number of quarters, dimes, nickels, pennies needed for the
* change.
* COMPLETED: 7/5/15
*/
//This Program utilizes Big Decimals for currency to avoid floating point artifacts
packageNumbers;
importjava.util.Scanner;
importjava.math.BigDecimal;
importjava.math.RoundingMode;
publicclassChangeReturn {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
BigDecimalcost;
BigDecimalpayment;
BigDecimalchange;
//Creates Big Decimals for the values of each coin as well as zero for use in compareTo
BigDecimalq= newBigDecimal(".25");
BigDecimald= newBigDecimal(".1");
BigDecimaln= newBigDecimal(".05");
BigDecimalp= newBigDecimal(".01");
BigDecimalnaught= newBigDecimal("0"); //Pretty bad but I couldn't figure out an alternative
//Creates variables to count each coin
intquarters = 0;
intnickels = 0;
intdimes = 0;
intpennies = 0;
//Asks for user input for the cost and Rounds it to 2 decimal place
System.out.println("What is the total cost?");
cost = scanner.nextBigDecimal();
cost= cost.setScale(2, RoundingMode.HALF_UP);
//Asks for user input for the payment by the customer and Rounds it to 2 decimal place
System.out.println("How much money was paid?");
payment = scanner.nextBigDecimal();
payment= payment.setScale(2, RoundingMode.HALF_UP);
//Checks that the payment is greater than the cost
if (payment.compareTo(cost) < 0)
System.out.println("Insufficient payment for given cost");
//calculates a single variable for the difference between cost and payment
change = payment.subtract(cost);
//While loop runs while there is any amount of change left. Greedy Algorithm subtracts coin values if possible
while(change.compareTo(naught) > 0){
if (change.compareTo(q) >= 0) {
quarters++;
change= change.subtract(q);
}
elseif (change.compareTo(d) >= 0) {
dimes++;
change= change.subtract(d);
}
elseif (change.compareTo(n) >= 0) {
nickels++;
change= change.subtract(n);
}
else {
pennies++;
change= change.subtract(p);
}
}
//Prints labeled output of the while loop
System.out.println(quarters + " Quarter(s)");
System.out.println(dimes + " Dime(s)");
System.out.println(nickels + " Nickel(s)");
System.out.println(pennies + " Pennies");
scanner.close();
}
}