Related
This is the question: A store clerk wants a program that calculates the exact change to give a customer with the minimum number of bills and coins. You should input the amount of the purchase and the amount of money tendered (given to the clerk) and then output the change required and the number of each bill and coin to make up the change. Remember you want the minimum number of coins and bills in each case.
** Plan out this program first, before writing any code **
A sample run of the program is shown below.
Change Making Program
Please enter the total purchase: $1.42
Please enter the amount tendered: $20.00
The change will be: $18.58
To make up this amount you will need:
1 ten-dollar bill
1 five-dollar bill
1 two-dollar coin
1 loonie
2 quarters
1 nickel
3 pennies
Thank you for using the Change Making Program
This is what I have so far:
package defaultpackage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ChangeMaker {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the total of your purchase: $");
double total = Integer.parseInt(stdin.readLine());
System.out.print("Please enter the amount of money tendered: $");
double tendered = Integer.parseInt(stdin.readLine());
double change = tendered - total;
System.out.print("Your change is: $" +change);
if (change > 99.99)
{
double hundreds = (change - (change % 100)) / 100;
System.out.print("Hundred-dollar bills: " + hundreds);
change = change - (hundreds * 100);
}
if (change > 49.99)
{
double fifties = (change - (change % 50)) / 50;
System.out.print("Fifty-dollar bills: " + fifties);
change = change - (fifties * 50);
}
if (change > 19.99)
{
double twenties = (change - (change % 20)) / 20;
System.out.print("Twenty-dollar bills: " + twenties);
change = change - (twenties * 20);
}
if (change > 9.99)
{
double tens = (change - (change % 10)) / 10;
System.out.print("Ten-dollar bills: " + tens);
change = change - (tens * 10);
}
if (change > 4.99)
{
double fives = (change - (change % 5)) / 5;
System.out.print("Five-dollar bills: " + fives);
change = change - (fives * 5);
}
if (change > 1.99)
{
double toonies = (change - (change % 2)) / 2;
System.out.print("Toonies: " + toonies);
change = change - (toonies * 2);
}
if (change > 0.99)
{
double loonies = (change - (change % 1)) / 1;
System.out.print("Loonies: " + loonies);
change = change - (loonies * 1);
}
if (change > 0.24)
{
double quarters = (change - (change % 0.25)) / 0.25;
System.out.print("Quarters: " + quarters);
change = change - (quarters * 0.25);
}
if (change > 0.09)
{
double dimes = (change - (change % 0.1)) / 0.1;
System.out.print("Dimes: " + dimes);
change = change - (dimes * 0.1);
}
if (change > 0.04)
{
double nickles = (change - (change % 0.05)) / 0.05;
System.out.print("Nickles: " + nickles);
change = change - (nickles * 0.05);
}
if (change > 0)
{
double pennies = (change - (change % 0.1)) / 0.1;
System.out.print("Pennies : " + pennies);
change = change - (pennies * 0.1);
}
}
}
Here is a solution to the problem you present. It produces exactly the desired output.
The code uses integer math to avoid the precision problems you will inevitably have when using floating point values to represent dollar amounts. To do this, input values are multiplied by 100 and treated as cents. When printing out dollar amounts, we divide by 100 to represent the values in dollars.
Another feature of this code is that it is data-driven. Rather than duplicate the logic for removing each denomination over and over, a table provides the information about each denomination, and then there is only one block of code that is run in a loop to deal with each denomination. The code deals with properly pluralizing each denomination name when appropriate, including the special case for "pennies".
package defaultpackage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.List;
class Denomination {
public Denomination(int value, String name, String pluralName) {
this.value = value;
this.name = name;
this.pluralName = pluralName;
}
public Denomination(int value, String name) {
this(value, name, null);
}
String getDescription(int count) {
String desc = this.name;
if (count > 1)
if (pluralName == null)
desc += 's';
else
desc = pluralName;
return desc;
}
public int getValue() {
return value;
}
private final int value;
private final String name;
private final String pluralName;
}
class ChangeMaker {
private static final List<Denomination> denominations = List.of(
new Denomination(10000, "one-hundred-dollar bill"),
new Denomination(5000, "fifty-dollar bill"),
new Denomination(2000, "twenty-dollar bill"),
new Denomination(1000, "ten-dollar bill"),
new Denomination(500, "five-dollar bill"),
new Denomination(200, "two-dollar coin"),
new Denomination(100, "loonie"),
new Denomination(25, "quarter"),
new Denomination(10, "dime"),
new Denomination(5, "nickel"),
new Denomination(1, "penny", "pennies")
);
public static void main(String[] args) throws IOException {
System.out.println("Change Making Program");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the total purchase: $");
int total = (int)(Double.parseDouble(stdin.readLine()) * 100);
System.out.print("Please enter the amount tendered: $");
int tendered = (int)(Double.parseDouble(stdin.readLine()) * 100);
int change = tendered - total;
System.out.printf("The change will be: $%.2f\n", change / 100.0);
System.out.println("To make up this amount you will need:");
for (Denomination denom: denominations) {
if (change == 0)
break;
if (change >= denom.getValue()) {
int count = change / denom.getValue();
if (count > 0) {
change = change - denom.getValue() * count;
System.out.printf("%d %s\n", count, denom.getDescription(count));
}
}
}
System.out.println("Thank you for using the Change Making Program");
}
}
Sample Run:
Change Making Program
Please enter the total purchase: $1.42
Please enter the amount tendered: $20.00
The change will be: $18.58
To make up this amount you will need:
1 ten-dollar bill
1 five-dollar bill
1 two-dollar coin
1 loonie
2 quarters
1 nickel
3 pennies
Thank you for using the Change Making Program
If the OP is asking this question to do a homework assignment, then I expect that this answer may be "too good". It may be using techniques not yet studied in class. Even if the OP could submit this as-is, I would encourage them to not do so. Instead, I'd suggest that they study this example, learn from it, and then incorporate what is learned into their own solution as appropriate. I encourage them to ask questions about the example, which I'd be happy to answer.
I have overseen the parseInt problem, but there is still another problem:
pennies = (change - (change % 0.1)) / 0.1;
...
change = change - (pennies * 0.1);
should be 0.01 instead of 0.1 - or just use what is left in change.
Advice: do not use double for money - lots of problems with rounding! (chances of change being short by one penny)
either use int/ long to represent cents, or
use BigDecimal
Note (change - (change % 100)) / 100 is basically the same as (int)(change / 100) - casting to int removes all decimals
I'm taking a course in Java and we haven't officially learned if statements yet. I was studying and saw this question:
Write a method called pay that accepts two parameters: a real number for a TA's salary, and an integer for the number hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive "overtime" pay of 1.5 times the normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0.
How do you solve this without using if statements? So far I've got this but I'm stuck on regular pay:
public static double pay (double salary, int hours) {
double pay = 0;
for (int i = hours; i > 8; i --) {
pay += (salary * 1.5);
}
}
To avoid direct use of flow control statements like if or while you can use Math.min and Math.max. For this particular problem using a loop would not be efficient either.
They may technically use an if statements or the equivalent, but so do a lot of your other standard library calls you already make:
public static double pay (double salary, int hours) {
int hoursWorkedRegularTime = Math.min(8, hours);
int hoursWorkedOverTime = Math.max(0, hours - 8);
return (hoursWorkedRegularTime * salary) +
(hoursWorkedOverTime * (salary * 1.5));
}
Since you've used a for loop, here's a solution just using two for loops.
public static double pay (double salary, int hours) {
double pay = 0;
for (int i = 0; i < hours && i < 8; i++) {
pay += salary;
}
for (int i = 8; i < hours; i++) {
pay += (salary * 1.5);
}
return pay;
}
This sums the salary for the regular hours up to 8, and then sums the salary for the overtime hours, where the overtime hours are paid at 1.5 * salary.
If there are no overtime hours, the second for loop will not be entered and will have no effect.
There's a few ways you can go about this, but it's hard to know what's allowed (if you can't even use if).
I would recommend using a while loop:
double pay = 0;
while (hoursWorked > 8) {
pay += (salary * 1.5);
hoursWorked--;
}
pay += (hoursWorked * salary);
The reason why this works is it decrements your hoursWorked to a value that is guaranteed to be less than or equal to 8 (assuming hoursWorked and salary are both greater than 0). If hoursWorked <= 8, then it will never enter the while loop.
If you really want to get hacky, you could use bitwise operators:
int otherHours = hours - 8;
int multiplier = (~otherHours & 0x80000000) >>> 31;
otherHours *= multiplier;
return otherHours * 0.5 * salary + hours * salary;
So basically, if otherHours is negative, there should be no overpay. We do this by selecting the sign bit of otherHours and shifting it to the least significant bit (with 0 padding) to mean either 1 or 0. After first negating it (if sign bit is 1, multiplier should be 0).
When you multiply this with otherHours it will be 0 in the case there are less than 8 hours, so as not to accidentally subtract any pay, when doing the final calculation.
Just for the record, here is a solution quite close to where you were stopped :
public static double pay (double salary, int hours) {
double pay = salary * hours;
for (int i = hours; i > 8; i --) {
pay += salary * 0.5;
}
}
You can simply use a ternary operator ?::
pay = hours*salary + ((hours > 8) ? (hours-8)*salary*0.5 : 0);
— pay a standard salary for the whole time worked, plus 50% for time above 8 hours (if any).
A cast to int can be abused for this purpose.
Note that the function
f(x) = 10/9 - 1/(x+1) = 1 + 1/9 - 1/(x+1)
is between 0 and 1 (exclusive) for 0 <= x < 8 and between 1 and 1.2 for x >= 8. Casting this value to int results 0 for x < 8 and in 1 for x >= 8.
This can be used in the calculation of the result:
public static double pay(double salary, int hours) {
int overtime = (int)(10d/9d - 1d/(hours+1));
return salary * (hours + 0.5 * overtime * (hours - 8));
}
Here's a way to do it using truncation from integer division, something that you probably have learnt at the start of java courses. Essentially the solution is a one liner that does not need if, loops, comparisons, libraries.
public static double pay(double salary, int hours) {
//Pay all hours as overtime, and then subtract the extra from the first 8 hours
double p1 = (hours * 1.5 * salary) - (4 * salary);
//In the case where the TA works for less than 8 hours,
//subtract all the extra so that ultimately, pay = salary * hours
double p2 = (hours * 0.5 * salary) - (4 * salary);
//When theres no overtime worked, m equals to 1.
//When there are overtime hours, m is equals to 0.
int m = (8 + 7) / (hours + 7);
//When there are overtime hours, pay is simply equal to p1.
//When there are no overtime hours, p2 is subtracted from p1.
return p1 - m*p2;
}
A solution which does not use any conditional(implicit or explicit)
Practically, you need to calculate hours * rate but if you have overtime then you need to add a bonus of the form overtime_hours * overtime_rate
in pseudo-code:
//you need to return:
hours * rate + is_overtime * overtime_time * overtime_rate
where
is_overtime = ceiling ( x / (x+1)) # this will be zero when x == 0, in rest 1
x = integer_division(hours, 8) # x == 0 if no overtime, in rest a positive integer
overtime_time = hours - 8
overtime_rate = (1.5 - 1) * rate = 0.5 * rate
(((hours/8)-1)*8 + hours%8)*salary*0.5 + (hours*salary)
overtime*salary*0.5 + (hours*salary)
((( 11/8 -1)*8 + 11%8)* 4*0.5 + ( 11* 4) = 50
(( 1 -1)*8 + 3)* 2 + 44 = 50
(( 0)*8 + 3)* 2 + 44 = 50
(( 0 + 3)* 2 + 44 = 50
6 + 44 = 50
So suppose we have (17 hours, 4 salary)
(((17/8)-1)*8 + 17%8)*4*0.5 + 17*4 = 86
( (2 -1)*8 + 1)*4*0.5 + 68 = 86
(8 + 1)*2 + 68 = 86
9*2 + 68 = 86
18 + 68 = 86
17-8=9 is overtime
9*4*1.5 + 8*4 = 9*6 + 32 = 54 + 32 = 86
You could creatively use a while statement as an if statement
while(hours > 8){
return ((hours - 8) * salary * 1.5) + (8 * salary);
}
return hours * salary;
Plenty of good and more efficient answers already, but here's another simple option using a while loop and the ternary operator:
double pay = 0.0;
while(hours > 0){
pay += hours > 8 ? wage * 1.5 : wage;
hours--;
}
return pay;
Using tanh to decide whether the hours are below 8 or not:
public static double pay (double salary, int hours) {
int decider = (int)(tanh(hours - 8) / 2 + 1);
double overtimeCompensation = 1.5;
double result = salary * (hours * (1 - decider) + (8 + (hours - 8) * overtimeCompensation) * decider);
return result;
}
The decider variable is 0 when hours is less than 8, otherwise 1. The equation basically contains two parts: the first hours * (1 - decider) would be for hours < 8, and (8 + (hours - 8) * overtimeCompensation) * decider for when hours >= 8. If hours < 8, then 1 - decider is 1 and decider is 0, so using the equations first part. And if hours >= 8, 1 - decider is 0 and decider is 1, so the opposite happens, the first part of the equation is 0 and the second is multiplied by 1.
public static double pay (double salary, int hours) {
int extra_hours = hours - 8;
extra_hours = extra_hours > 0 ? extra_hours : 0;
double extra_salary = (salary * 1.5) * extra_hours;
double normal_salary = extra_hours > 0 ? salary * 8 : salary * hours;
return normal_salary + extra_salary;
}
You can use ternary operator.
public static double pay(double salary, int hours){
//get the salary and hours
return hours>8?(1.5*hours-4)*salary:hours*salary;
}
Some programming languages have explicit pattern-matching features. So for example, in XSLT, a given template will fire if the node being processed matches a given XPATH query better than other templates in your programme.
This kind of "declarative" programming is a level of abstraction higher than what you have in Java, but you still have the switch statement, which gives you the ability to control your flow with a "matching" approach rather than using explicit if-else constructs.
public static double pay (double salary, int hours) {
double pay = 0;
for (int i = hours; i > 0;i--){
switch (i){
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
pay += (salary);
break;
default:
pay += (salary * 1.5);
break;
}
}
return pay;
}
Having said that, for your specific example, what you really do need is an if statement. The switch approach will work, but it's a bit contrived.
In Tsql
DECLARE #amount float = 4.00
, #hrs int = 11
DECLARE #overtime int
, #overeight bit
SET #overeight = ((#hrs/8) ^ 1)
SET #overtime = CEILING((#hrs%8) / ((#hrs%8) + 1.0)) * ~#overeight
--SELECT #hrs * #amount
SELECT ((#hrs-(#hrs%8 * ~#overeight)) * #amount) + ( #overtime * (#hrs%8 * (#amount * 1.5)))
(from Valentin above)
I am writing a program that will simulate a cash register change calculator. It should print the change and how to give back the change ( number of twenty, tens, fives, quarters, dimes, etc).
The problem is that when I compile the program, I get a big number. I've tried rounding it down but it doesn't work. ALSO, I don't know if it is caused by the change not being rounded but I won't get the number of cents, I only get 1 $10 bill.
p.s. I am taking a high school CS course and right now I can't use other methods of rounding it, I know there is a way like the one I attempted below (casting and stuff) which I am allowed to use at the moment.
Thank you.
public class changeCash
{
public static void main(String[] args)
{
double cost = 68.90;
double amtPaid = 80.00;
double change = 0;
int twentyBill= 0;
int tenBill = 0;
int fiveBill = 0;
int oneBill = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
change = amtPaid - cost;
change = ((int)change * 10) / 10.0;
System.out.println("Your change is " +"$" + change);
double back = amtPaid - cost;
if(back >= 20)
{
twentyBill++;
back -= 20;
System.out.println(twentyBill + " $20 bill(s)");
}
else if(back >= 10)
{
tenBill++;
back -= 10;
System.out.println(tenBill + " $10 bill(s)");
}
else if(back >= 5)
{
fiveBill++;
back -= 5;
System.out.println(fiveBill + " $5 bills(s)");
}
else if(back >= 1)
{
oneBill++;
back -= 1;
System.out.println(oneBill + " $1 bills(s)");
}
else if(back >= 0.25)
{
quarters++;
back -= 0.25;
System.out.println(quarters + " qaurter(s)");
}
else if(back >= 0.10)
{
dimes++;
back -= 0.10;
System.out.println(dimes + " dime(s)");
}
else if(back >= 0.05)
{
nickels++;
back -= 0.05;
System.out.println(nickels + " nickel(s)");
}
else if(back >= 0.01)
{
pennies++;
back -= 0.01;
System.out.println(pennies + " penny(ies)");
}
}
}
Couple of issues. First, smaller one:
change = amtPaid - cost;
Change is 11.1, as it should be, but then:
change = ((int)change * 10) / 10.0;
Casts take precedence over arithmetic, so first (int)change happens (which results in 11), then it is multiplied by 10, then divided by 10.0, and you end up with 11.0 instead of 11.1.
But your bigger problem is in your if statements. You have a series of if...else. Once one of these executes, the remainder of the else blocks will not. So when you have e.g.:
if (back >= 20) {
...
} else if (back >= 10) {
...
} else if (back >= 5) {
...
} else ...
As soon as one hits, it's done. If back >= 20 is false it goes to the next. Then if back >= 10 is true, it executes that, then doesn't execute the rest, so you would want to separate them, e.g.:
if (back >= 20) {
...
}
if (back >= 10) {
...
}
if (back >= 5) {
...
}
...
That'll get you closer, but you're still not quite there. For example, what if your change is 40? That will be two 20's. But your if statement will only take away a single 20. To that end, a while loop would be appropriate. It also more accurately reflects reality. In real life if you had to give somebody $40, you wouldn't just give them a single $20 and walk away, you'd get a dirty look. You'd keep giving them $20's until the amount you owed them was less than $20. So for example:
while (back >= 20) {
...
}
while (back >= 10) {
...
}
while (back >= 5) {
...
}
...
You want your code to reflect the logic you would use in reality.
Regarding your question in comments:
... why do I get $11.099999999999994 instead of just 11.1?
Floating-point rounding error. Decimal numbers are not 100% accurate; "11.1" can't be represented precisely. You have a couple of ways to work around it. You could round to two decimals when you display the number, e.g. System.out.printf("%.2f", change). However, you may want to use int and store the number of cents, rather than using double and storing the number of dollars. Working with integers is more precise, and actually, when working with currency in important applications, integers are often used for this reason.
Simpler Solution
double d = 2.99999999;
long l = (long) d;
Math.class, floor function
double d = Math.floor(2.55555) //result: 2.0
Returns the largest (closest to positive infinity) double value that
is less than or equal to the argument and is equal to a mathematical
integer
Find below the code which works well. Tested with different values. We want to avoid more than 2 decimal places hence I have added several utility methods just to do that.
Uncomment different cost values to see its working in different scenarios.
public class ChangeCash {
public static void main(String[] args) {
double cost = 65.90;
// cost = 68.33;
// cost = 42.27;
double amtPaid = 80.00;
double change = 0;
int twentyBill = 0;
int tenBill = 0;
int fiveBill = 0;
int oneBill = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
change = amtPaid - cost;
System.out.format("Your change is $ %.2f", decimalCeil(change, true));
System.out.println();
double back = decimalCeil(change, true);
if (back >= 20) {
twentyBill++;
back -= 20;
System.out.println(twentyBill + " $20 bill(s)");
}
if (back >= 10) {
tenBill++;
back -= 10;
System.out.println(tenBill + " $10 bill(s)");
}
if (back >= 5) {
fiveBill++;
back -= 5;
System.out.println(fiveBill + " $5 bills(s)");
}
if (back >= 1) {
oneBill = (int) (back * 10) / 10;
back -= oneBill;
System.out.println(oneBill + " $1 bills(s)");
}
if (decimalCeil(back) >= 0.25) {
quarters = (int) (back * 100) / 25;
back = correct2DecimalPlaces(back, 25);
System.out.println(quarters + " qaurter(s)");
}
back = (int) (decimalCeil(back, true) * 100);
if (back >= 10) {
dimes = (int) (back / 10);
back = back % 10;
System.out.println(dimes + " dime(s)");
}
if (back >= 5) {
nickels = (int) (back / 5);
back = back % 5;
System.out.println(nickels + " nickel(s)");
}
if (back >= 1) {
pennies = (int) back;
System.out.println(pennies + " penny(s)");
}
}
private static double correct2DecimalPlaces(double back, int modulo) {
int correctTwoPlaces = (int) (back * 100) % modulo;
back = (double) correctTwoPlaces / 100;
return back;
}
private static double decimalCeil(double change) {
int temp = (int) (change * 100);
double tempWithCeil = Math.ceil(temp);
double answer = tempWithCeil / 100;
return answer;
}
private static double decimalCeil(double change, boolean decimalThreePlaces) {
double temp = change * 1000;
double tempWithCeil = Math.ceil(temp);
double answer = tempWithCeil / 1000;
return answer;
}
}
I'm currently working on an assignment for school where I need to write a program that it needs to return your change in this mode
Input:
purchaseAmount: $12.45
givenAmount: $15.00
Output:
Change: $2.55
2 one dollar bills
2 quarters
1 nickel
But, if I work with this case scenario it works fine. Now, If I want this scenario to work this what I get
Input:
purchaseAmount: $19.51
givenAmount: $50.01
Output:
Twenty dollar bill 1
Ten dollar bill: 1
Quarters: 1
Dimes: 2
Pennies: 4
Which is incorrect since I'm returning to the costumer 30.49 instead of 30.5
Can't figure out whats the issue here.
Thanks
boolean isFiveBillOn = false, isTwentybillOn = false, isTenbillOn = false, isDollarOn = false, isQuartersOn = false, isDimesOn = false, isNicklesOn = false, isPenniesOn = false;
//retrieve amount due
String moneyd = JOptionPane.showInputDialog("Enter the amount due");
double amountd = Double.parseDouble(moneyd);
String moneyr = JOptionPane.showInputDialog("Enter amount you would like to pay");
double amountr = Double.parseDouble(moneyr);
//calculate difference
double difference = (amountr - amountd);
//convert to pennies
int balance = (int)(difference * 100);
//twenty dollar bill
int twentydollars = balance / 2000;
balance = (balance % 2000);
if (twentydollars > 0) {
isTwentybillOn = true;
}
//ten dollar bill
int tendollars = balance / 1000;
balance = (balance % 1000);
if (tendollars > 0) {
isTenbillOn = true;
}
//five dollar bill
int fivedollars = balance / 500;
balance = (balance % 500);
if (fivedollars > 0) {
isFiveBillOn = true;
}
//dollar bill
int dollars = balance / 100;
balance = (balance % 100);
if (dollars > 0) {
isDollarOn = true;
}
//quartes
int quarters = balance / 25;
balance = (balance % 25);
if (quarters > 0) {
isQuartersOn = true;
}
//dimes
int dimes = balance / 10;
balance = (balance % 10);
if (dimes > 0) {
isDimesOn = true;
}
//nickles
int nickles = balance / 5;
balance = (balance % 5);
if (nickles > 0){
isNicklesOn = true;
}
//pennies
int pennies = balance / 1;
balance = (balance % 1);
if (pennies > 0){
isPenniesOn = true;
}
//checking for difference over 0
if (difference < 0) {
JOptionPane.showMessageDialog(null, "The amount received can't be less than the amount owned");
} else {
// Returning Message
} if (isTwentybillOn) {
System.out.println("Twenty dollar bill " + twentydollars);
} if (isTenbillOn) {
System.out.println("Ten dollar bill: " + tendollars);
} if (isDollarOn) {
System.out.println("One Dollar Bill: " + dollars);
} if (isQuartersOn) {
System.out.println("Quarters: " + quarters);
} if (isDimesOn) {
System.out.println("Dimes: " + dimes);
} if (isNicklesOn) {
System.out.println("Nickles: " + nickles);
} if (isPenniesOn) {
System.out.println("Pennies: " + pennies);
} else {
System.out.println("Thanks! have a good day");
}
}
You should never use a double or any other floating-point data type to represent money. The reason is that they can't represent all values exactly. For example, the following line:
System.out.println(new BigDecimal(0.1));
prints
0.1000000000000000055511151231257827021181583404541015625
For a longer explanation why, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.
I suggest using BigDecimal instead.
An alternative if you only want to use primitives is to use an int to store the currency value in cents instead, and divide by 100 when displaying the value.
Ok so i need to make a program to ask me for an amount of money, then I need it to tell me the least amount of coins to make it. The coins I can use are: dollars, quarters, dimes, nickels, and pennies. For example, When I run the program it's supposed to look like this:
> run Coins
Enter the amount of given money:
[1.73]
Give the seller 8 coins:
1 dollars,
2 quarters,
2 dime,
0 nickels,
3 pennies.
This is What I have so far:
import java.util.Scanner;
class Coins {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
double money;
System.out.println("Enter the amount of money ");
money = input.nextDouble();
while (money > 0.0 ){
if (money >= 1) {
System.out.println(money/1+"dollars");
money -= 1;
}
else if (money>=.25) {
System.out.println(money/.25+"quarters");
money-=.25;
}
else if (money>=.10) {
System.out.println(money/.10+"Dimes");
money-=.10;
}
else if (money>=.05) {
System.out.println(money/.05+"Nickels");
money-=.05;
}
else if (money>=.01) {
System.out.println(money/.01+"Penny");
money-=.01;
}
}
}
}
The part I need help with is this: If I run the program and enter the amount 1.73, the way I have the code written, it takes the number 1.73, divides it by 1, and prints "1.73 dollars". I need a way to get rid of the decimal part so instead of printing "1.73 dollars", it prints "1 dollar". But I'm not sure how to do this. I tried converting it to an int but it messes up the flow of the other statements. Please help me.
You should use the combination of floor with casting to double, the following code works:
class Coins {
public static void main (String args[]) {
double money = 1.73;
while (money > 0.0 ){
if (money >= 1) {
System.out.println(Math.floor(money/1)+" dollars");
money -= Math.floor(money/1)*(double)1;
}
else if (money>=.25) {
System.out.println(Math.floor(money/.25)+" quarters");
money-=Math.floor(money/.25)*(double).25;
}
else if (money>=.10) {
System.out.println(Math.floor(money/.10)+" Dimes");
money-=Math.floor(money/.10)*(double).10;
}
else if (money>=.05) {
System.out.println(Math.floor(money/.05)+" Nickels");
money-=Math.floor(money/.05)*(double).05;
}
else if (money>=.01) {
System.out.println(Math.round(money/.01)+" Penny");
money-=Math.round(money/.01)*(double).01;
}
}
}
}
Another bug you had:
You should subtract Math.floor(money/XXX)*(double)XXX not (double)XXX
You need get rid of the remainder after the divisions. You can use Math.floor() for this:
class Coins {
public static void main (String args[]) {
double money = 1.73;
int dollars = (int) Math.floor(money/1);
money -= dollars * 1;
int quarters = (int) Math.floor(money/0.25);
money -= quarters * 0.25;
int dimes = (int) Math.floor(money/0.10);
money -= dimes * 0.10;
int nickels = (int) Math.floor(money/0.05);
money -= nickels * 0.05;
int pennies = (int) Math.round(money * 100);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
Resulting in:
Dollars: 1
Quarters: 2
Dimes: 2
Nickels: 0
Pennies: 3