So I need help on how to calculate how much change to give back to a customer. I need the program to give change in the least bills and coins as possible.

Ex. Customer's item costs $13.37.
He/She pays $20.

Program gives back:

One $5 Bill
One $1 Bill
Two Quarters
One Ten Cent
Three One Cents

Bills used:

Any kind of bills/coins used regularly today in the United States up to $20.

No Half Dollars, $2 dollar bills, and Dollar coins.

I've gotten most of my code down, but the math portion of it is really, really bad!

import javax.swing.JOptionPane;


public class Project {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		double amountGiven = 0;
		double changeGiven = 0;
		double amountNeeded = 0;
		final double ONE_CENT = 0.01;
		final double FIVE_CENT = 0.05;
		final double TEN_CENT = 0.10;
		final double TWENTYFIVE_CENT = 0.25;
		final int ONE_DOLLAR = 1;
		final int FIVE_DOLLAR = 5;
		final int TEN_DOLLAR = 10;
		final int TWENTY_DOLLAR = 20;
		
		amountNeeded = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the cost for an item!"));
		
		JOptionPane.showMessageDialog(null, "The customer needs to pay: $" + amountNeeded);
		
		amountGiven = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter an amount a customer payed!"));
		
		final double tempDouble = amountGiven;
		
		changeGiven = Math.round(tempDouble - amountNeeded);
		 
		
		int billBack20 = (int) (tempDouble / TWENTY_DOLLAR);
		int billBack10 = (int) (tempDouble / TEN_DOLLAR);
		int billBack5 = (int) (tempDouble / FIVE_DOLLAR);
		int billBack1 = (int) (tempDouble / ONE_DOLLAR);
		
		int coinBack25 = (int) (tempDouble / TWENTYFIVE_CENT);
		int coinBack10 = (int) (tempDouble / TEN_CENT);
		int coinBack5 = (int) (tempDouble / FIVE_CENT);
		int coinBack1 = (int) (tempDouble / ONE_CENT);
		
			
		if ( changeGiven < 0 == true ) { JOptionPane.showMessageDialog(null, "Stop being cheap, and pay up!");
		if ( changeGiven < 0 == false )  JOptionPane.showMessageDialog(null, "The amount you will get back is: " + changeGiven);}
		
		
		JOptionPane.showMessageDialog(null,
		"You will be given back:\n" +
		"Twenty Dollar Bills:" + billBack20 +
		"\nTen Dollar Bills:" + billBack10 +
		"\nFive Dollar Bills:" + billBack5 +
		"\nOne Dollar Bills:" + billBack1 +
		"\nand" +
		"\nTwentyfive Cents:" + coinBack25 +
		"\nTen Cents:" + coinBack10 +
		"\nFive Cents:" + coinBack5 +
		"\nOne Cents:" + coinBack1);
		
				
		


		

	}

}

Thanks!

Recommended Answers

All 23 Replies

I found this: http://www.cvanbibber.com/code_examples/java-change-calculator/

But...

$1-$0.65 = $0.35

Change given by this program is: 1 Quarter, and 2 Nickels...

But the program I'm trying to write would put out:

1 Quarter, and 1 Dime...

Also, his program:

Total Cost: 27.94, Amount Paid: 28.0

The total change is: 0.06
Nickle(s): 1

Missing 1 cent...

1. Forget about some crummy buggy thing you found on the net.
2. You are nearly there. On line 35 you work out how many 20's, but then you need to subtract that from the balance remaining.

Could you show me an example?

I kind of got it to work on everything but the one dollar and the coins.

Next thing I need to do is to make it give the lowest amount of bills and coins possible.

Ex. 10.35

Change should be:
1 Ten Dollar Bill
1 quarter
1 Dime

NOT:

2 Five dollar bills
3 dimes
1 nickel

etc.

Member Avatar for hfx642

That's the problem with cash registers these days.
They do all the work for you and you don't learn how to make change.
HINT: Count UP!!!
You know how much you have to give back.
Start with pennies -> nickles.
nickles and dimes -> quarters
quarters -> singles
singles and twos -> fives
etc., etc.
Remove how much you have added, from what you have to give back.

commented: i cannot see any reason for down-vote +9

Could you give a code example?

I'm in High School, and this project is for AP Computer Science A. Unfortunately, the teacher haven't talked about this project much, so I'm left clueless on some stuff such as

2. You are nearly there. On line 35 you work out how many 20's, but then you need to subtract that from the balance remaining.

and

HINT: Count UP!!!
You know how much you have to give back.
Start with pennies -> nickles.
nickles and dimes -> quarters
quarters -> singles
singles and twos -> fives
etc., etc.
Remove how much you have added, from what you have to give back.

import javax.swing.JOptionPane;


public class Project {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		double amountGiven = 0;
		double amountNeeded = 0;
		final double ONE_CENT = 0.01;
		final double FIVE_CENT = 0.05;
		final double TEN_CENT = 0.10;
		final double TWENTYFIVE_CENT = 0.25;
		final int ONE_DOLLAR = 1;
		final int FIVE_DOLLAR = 5;
		final int TEN_DOLLAR = 10;
		final int TWENTY_DOLLAR = 20;
		
		amountNeeded = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the cost for an item!"));
		
		JOptionPane.showMessageDialog(null, "The customer needs to pay: $" + amountNeeded);
		
		amountGiven = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter an amount a customer payed!"));
		
		final double tempDouble = amountGiven;
		
		final double changeGiven = tempDouble - amountNeeded;
		 
		
		int billBack20 = (int) (changeGiven / TWENTY_DOLLAR);
		int billBack20Text = (int) Math.round((changeGiven - billBack20) / 20);
		int billBack10 = (int) (changeGiven / TEN_DOLLAR);
		int billBack10Text = (int) Math.round((changeGiven - billBack10) / 10);
		int billBack5 = (int) (changeGiven / FIVE_DOLLAR);
		int billBack5Text = (int) Math.round((changeGiven - billBack5) / .5);
		int billBack1 = (int) (changeGiven / ONE_DOLLAR);
		int billBack1Text = (int) Math.round((changeGiven - billBack1) / .1);
		
		int coinBack25 = (int) (changeGiven / TWENTYFIVE_CENT - (changeGiven / amountGiven));
		int coinBack10 = (int) (changeGiven / TEN_CENT - (changeGiven / amountGiven));
		int coinBack5 = (int) (changeGiven / FIVE_CENT - (changeGiven / amountGiven));
		int coinBack1 = (int) (changeGiven / ONE_CENT - (changeGiven / amountGiven));
		
		if ( billBack20Text > billBack10Text == true ) { billBack10 = 0; }
			
		if ( changeGiven <= 0 == true ) { JOptionPane.showMessageDialog(null, "Stop being cheap, and pay up!"); }
		else { 
		JOptionPane.showMessageDialog(null, "The amount you will get back is: " + changeGiven + "\n" + 
		"You will be given back:\n" +
		"Twenty Dollar Bills:" + billBack20Text +
		"\nTen Dollar Bills:" + billBack10Text +
		"\nFive Dollar Bills:" + billBack5Text +
		"\nOne Dollar Bills:" + billBack1Text +
		"\nand" +
		"\nTwentyfive Cents:" + coinBack25 +
		"\nTen Cents:" + coinBack10 +
		"\nFive Cents:" + coinBack5 +
		"\nOne Cents:" + coinBack1);
		
				
		


		}

	}

}

That's what I have so far now, and it ain't working out for me. ):

I guess you could call me a dumbass for not knowing simple math.

if (billBack20 < billBack10 == true) { billBack10 = 0; } else { billBack20 = 0; }
		if (billBack10 < billBack5 == true) { billBack5 = 0; } else { billBack10 = 0; }
		if (billBack5 < billBack1 == true) { billBack1 = 0; } else { billBack5 = 0; }
		
		if (coinBack25 < coinBack10 == true) { coinBack10 = 0; } else { coinBack25 = 0; }
		if (coinBack10 < coinBack5 == true) { coinBack5 = 0; } else { coinBack10 = 0; }
		if (coinBack5 < coinBack1 == true) { coinBack1 = 0; } else { coinBack5 = 0; }

Hmm... Can someone fix that for me?

Latest code:

import javax.swing.JOptionPane;


public class Project {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		double amountGiven = 0;
		double amountNeeded = 0;
		final double ONE_CENT = 0.01;
		final double FIVE_CENT = 0.05;
		final double TEN_CENT = 0.10;
		final double TWENTYFIVE_CENT = 0.25;
		final int ONE_DOLLAR = 1;
		final int FIVE_DOLLAR = 5;
		final int TEN_DOLLAR = 10;
		final int TWENTY_DOLLAR = 20;
		
		amountNeeded = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the cost for an item!"));
		
		JOptionPane.showMessageDialog(null, "The customer needs to pay: $" + amountNeeded);
		
		amountGiven = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter an amount a customer payed!"));
		
		final double tempDouble = amountGiven;
		
		final double changeGiven = tempDouble - amountNeeded;
		 
		
		int billBack20 = (int) (((changeGiven * 100) / (TWENTY_DOLLAR * 100)));
		int billBack10 = (int) (((changeGiven * 100) / (TEN_DOLLAR * 100)));
		int billBack5 = (int) (((changeGiven * 100) / (FIVE_DOLLAR * 100)));
		int billBack1 = (int) (((changeGiven * 100) / (ONE_DOLLAR * 100)));
		
		int coinBack25 = (int) ((changeGiven * 25) / (TWENTYFIVE_CENT * 25));
		int coinBack10 = (int) ((changeGiven * 10) / (TEN_CENT * 10));
		int coinBack5 = (int) ((changeGiven * 5) / (FIVE_CENT * 5));
		int coinBack1 = (int) ((changeGiven * 1) / (ONE_CENT * 1));
		
		
		
		if (billBack20 < billBack10 == true) { billBack10 = 0; } else { billBack20 = 0; }
		if (billBack10 < billBack5 == true) { billBack5 = 0; } else { billBack10 = 0; }
		if (billBack5 < billBack1 == true) { billBack1 = 0; } else { billBack5 = 0; }
		
		if (coinBack25 < coinBack10 == true) { coinBack10 = 0; } else { coinBack25 = 0; }
		if (coinBack10 < coinBack5 == true) { coinBack5 = 0; } else { coinBack10 = 0; }
		if (coinBack5 < coinBack1 == true) { coinBack1 = 0; } else { coinBack5 = 0; }
		
		
		
		
		if ( changeGiven < 0 == true ) { JOptionPane.showMessageDialog(null, "Stop being cheap, and pay up!"); }
		else { 
		JOptionPane.showMessageDialog(null, "The amount you will get back is: $" + changeGiven + "\n" + 
		"You will be given back:\n" +
		"Twenty Dollar Bill(s): " + billBack20 +
		"\nTen Dollar Bill(s): " + billBack10 +
		"\nFive Dollar Bill(s): " + billBack5 +
		"\nOne Dollar Bill(s): " + billBack1 +
		"\nand" +
		"\nQuarter(s): " + coinBack25 +
		"\nDimes(s): " + coinBack10 +
		"\nNickel(s) : " + coinBack5 +
		"\nPenny/Pennies: " + coinBack1);
		
				
		


		}

	}

}

I need to get started on my AP English homework soon. Please respond with a fix to the code, and not just hints. I'm not good with hints. That's why this question is still open. ;)

commented: hints help more than doing it for you, surely? -3

Almost no progress... >.>

import javax.swing.JOptionPane;


public class Project {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		double amountGiven = 0;
		double amountNeeded = 0;
		final double ONE_CENT = 0.01;
		final double FIVE_CENT = 0.05;
		final double TEN_CENT = 0.10;
		final double TWENTYFIVE_CENT = 0.25;
		final int ONE_DOLLAR = 1;
		final int FIVE_DOLLAR = 5;
		final int TEN_DOLLAR = 10;
		final int TWENTY_DOLLAR = 20;
		
		amountNeeded = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter the cost for an item!"));
		
		JOptionPane.showMessageDialog(null, "The customer needs to pay: $" + amountNeeded);
		
		amountGiven = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter an amount a customer payed!"));
		
		final double tempDouble = amountGiven;
		
		final double changeGiven = tempDouble - amountNeeded;
		 
		
		int billBack20 = (int) (((changeGiven * 100) / (TWENTY_DOLLAR * 100)));
		int billBack10 = (int) (((changeGiven * 100) / (TEN_DOLLAR * 100)));
		int billBack5 = (int) (((changeGiven * 100) / (FIVE_DOLLAR * 100)));
		int billBack1 = (int) (((changeGiven * 100) / (ONE_DOLLAR * 100)));
		
		int coinBack25 = (int) ((changeGiven * 25) / (TWENTYFIVE_CENT * 25));
		int coinBack10 = (int) ((changeGiven * 10) / (TEN_CENT * 10));
		int coinBack5 = (int) ((changeGiven * 5) / (FIVE_CENT * 5));
		int coinBack1 = (int) ((changeGiven * 1) / (ONE_CENT * 1));
		

		
		int billBack20Text = 0;
		int billBack10Text = 0;
		int billBack5Text = 0;
		int billBack1Text = 0;
		
		int coinBack25Text = 0;
		int coinBack10Text = 0;
		int coinBack5Text = 0;
		int coinBack1Text = 0;
		
		if (billBack20 <= billBack10 == true) { billBack20Text = billBack20; } else { billBack20Text = 0; }
		if (billBack10 <= billBack5 == true) { billBack10Text = billBack10; } else { billBack10Text = 0; }
		if (billBack5 <= billBack1 == true) { billBack5Text = billBack5; } else { billBack5Text = 0; }
		if (billBack1 <= 0 == true) { billBack1Text = billBack1; } else { billBack1Text = 0; }
		 
		if (coinBack25 <= coinBack10 == true) { coinBack25Text = coinBack25; } else { coinBack25Text = 0; }
		if (coinBack10 <= coinBack5 == true) { coinBack10Text = coinBack10; } else { coinBack10Text = 0; }
		if (coinBack5 <= coinBack1 == true) { coinBack5Text = coinBack5; } else { coinBack5Text = 0; }
		if (coinBack1 <= 0 == true) { coinBack1Text = coinBack1; } else { coinBack1Text = 0; }
		
		
		
		if ( changeGiven < 0 == true ) { JOptionPane.showMessageDialog(null, "Stop being cheap, and pay up!"); }
		else { 
		JOptionPane.showMessageDialog(null, "The amount you will get back is: $" + changeGiven + "\n" + 
		"You will be given back:\n" +
		"Twenty Dollar Bill(s): " + billBack20Text +
		"\nTen Dollar Bill(s): " + billBack10Text +
		"\nFive Dollar Bill(s): " + billBack5Text +
		"\nOne Dollar Bill(s): " + billBack1Text +
		"\nand" +
		"\nQuarter(s): " + coinBack25Text +
		"\nDimes(s): " + coinBack10Text +
		"\nNickel(s) : " + coinBack5Text +
		"\nPenny/Pennies: " + coinBack1Text);
		
				
		


		}

	}

}

Time for a reality check.
There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in coding your homework for you. Bumping your own thread and sending PMs is not going to encourage anyone to help. Just re-read what you posted earlier:

I need to get started on my AP English homework soon. Please respond with a fix to the code, and not just hints. I'm not good with hints.

Nobody speaks to me like that, so you can finish this one without me.

commented: Post is not helpful. Please go improve your attitude. -1
commented: No reason for a red mark from a brat with a sense of entitlement. +15

Time for a reality check.
There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in coding your homework for you. Bumping your own thread and sending PMs is not going to encourage anyone to help. Just re-read what you posted earlier:

Nobody speaks to me like that, so you can finish this one without me.

No one gave an coded example. Even one line could of helped. But hey, whatever. You didn't help me one bit. You may be dismissed from this thread.

I'm not just trying to pass the class. I'm trying to understand the code a bit more. A coded example would of let me see what went wrong in my code, enabling me to be able to correct it in the future.

wrong this code missed a few astronomic constants, everything is up-side-down,

This is probably too late but I'll post it anyway.

@hfx642
Cashiers count up so as not to have to do the math. This is because people are much better at determining the unit boundaries for currency than are computers.
Counting up using a computer algorithm would be more complex than testing largest first as the OP is doing.

@CoolPrizes
The first hint you got from JamesCherill was the best one. (But you seemed to ignore it.)
This is a code snippet of what is meant by "you need to subtract that from the balance remaining".

double changeLeft = changeGiven;

            int billBack20 = (int)(changeLeft / TWENTY_DOLLAR);
            changeLeft = Math.Round(changeLeft - (billBack20 * TWENTY_DOLLAR), 2);

            int billBack10 = (int)(changeLeft / TEN_DOLLAR);
            changeLeft = Math.Round(changeLeft - (billBack10 * TEN_DOLLAR), 2);

The rest is up to you.

P.S. I tried using changeLeft -= billBack10 * TEN_DOLLAR; but when it calculated 10.35 - 10 the result was 0.3499999999999.
This resulted in a missing penny at the end. (Probably the same error is in that sample code you found).

commented: thanks. I compared it to the sample code and realized my problem. +1

P.S. I tried using changeLeft -= billBack10 * TEN_DOLLAR; but when it calculated 10.35 - 10 the result was 0.3499999999999.
This resulted in a missing penny at the end. (Probably the same error is in that sample code you found).

This kind of thing is inevitable when using float/double, and often results in all kinds of ad-hoc rounding that cannot be proved to work 100% of the time. Best solution is to hold all the monetary amounts as integer cents.

Best solution is to hold all the monetary amounts as integer cents.

That would be fine for this task but generally when calculating monetary values such as interest, you do not want to round anything until the last possible moment.

Did you mean BigDecimal? That would certainly be an appropriate class for currency.

commented: correct +9

changeLeft = Math.Round(changeLeft - (billBack20 * TWENTY_DOLLAR), 2);

Just noticed that the Math.Round in this is not right (it is a .Net overload that takes a power as a second parameter).:$
The correct code pattern is

changeLeft = Math.Round((changeLeft - (billBack20 * TWENTY_DOLLAR)) * 100) / 100;

@nick.crane please read this post by @EJP, be sure that this man has a true,

float has only 8 singnificant number possitions, otherwise loose precision in numeric form, double 11 or 12, you can test that by using String.format or DecimalFormat (by @Hovercraft Full Of Eels)

my post here only compare number output v.s. MsExcell, because everywhere is MsExcell, then I can't interesting about real number precision

@nick.crane please read this post by @EJP, be sure that this man has a true,

float has only 8 singnificant number possitions, otherwise loose precision in numeric form, double 11 or 12, you can test that by using String.format or DecimalFormat (by @Hovercraft Full Of Eels)

my post here only compare number output v.s. MsExcell, because everywhere is MsExcell, then I can't interesting about real number precision

Firstly, float is accurate to 7 (7.225) significant digits and double to 15 (15.995).

Re: post by @EJP: I question the accuracy of his test. if ((d % 0.01) != 0.0) is using the floating point modulus calculation!!
How accurate is that?
A better test is to compare the rounding against an integer equivalent.
Something like this.

public class RoundingCounterExample
    {
        private static double roundOff(double x, int position)
        {
            double a = x;
            double temp = Math.pow(10.0, position);
            a *= temp;
            a = Math.round(a);
            return (a / temp);
        }

        public static void main(String[] args)
        {
            int count = 0, errors = 0;
            // integer loop (not inaccurate double loop)
            for (int x = 0; x < 100000; x++)
            {
                count++;
                // get rounded value using integers
                // integer division always rounds down but Math.round rounds to nearest so use +50 to simulate this
                int y = (x + 50) / 100;
                // divide beyond integer division to test rounding function (d is now 1000 x smaller than y + a little bit)
                double d = x / 100000.0;
                // round d to 3 decimal places (rounded = y/1000) (little bit removed)
                double rounded = roundOff(d, 3);
                // multiply back up to integer level to test against y
                int z = (int)(rounded*1000.0);
                // check if value is OK
                if (y != z)
                {
                    // count errors
                    errors++;
                }
            }
            // report error incidents.
            System.out.println(count + " trials " + errors + " errors");
        }
    }

Note: I'm not a Java programmer. I used .Net to test this code and the error incident came out at 12 in 100000! By all means check it out for yourself.

commented: good suggestion +1 +9

that's about precision for Algebra, or if we'll count some formulas by pen on the paper, but PL ...

:-) not :-) for real precision we have to look for BigDecimal (by @JamesCherrill) or by using String.Format(),

but if we needed to compare with output from MsExcel(as I know MsOffice is wrotten in MFC) then doesn't matter if we use your code or my code,

btw result is is same from C++ or .Net and you can test this difference with string.format()

This is probably too late but I'll post it anyway.

@hfx642
Cashiers count up so as not to have to do the math. This is because people are much better at determining the unit boundaries for currency than are computers.
Counting up using a computer algorithm would be more complex than testing largest first as the OP is doing.

@CoolPrizes
The first hint you got from JamesCherill was the best one. (But you seemed to ignore it.)
This is a code snippet of what is meant by "you need to subtract that from the balance remaining".

double changeLeft = changeGiven;

            int billBack20 = (int)(changeLeft / TWENTY_DOLLAR);
            changeLeft = Math.Round(changeLeft - (billBack20 * TWENTY_DOLLAR), 2);

            int billBack10 = (int)(changeLeft / TEN_DOLLAR);
            changeLeft = Math.Round(changeLeft - (billBack10 * TEN_DOLLAR), 2);

The rest is up to you.

P.S. I tried using changeLeft -= billBack10 * TEN_DOLLAR; but when it calculated 10.35 - 10 the result was 0.3499999999999.
This resulted in a missing penny at the end. (Probably the same error is in that sample code you found).

Wow. I went way off road. I tried to do it with the if-else statements, but completely failed it. I still don't understand how it ignores the other bills.

Does it simply subtract from the total every time until it hits 0.00, and if a certain bill is near the total amount, it subtracts the current total amount away from it (ex. 11.50, nearest bill: 10. 1.50 left.)? If so, I can't believe I turned something so easy into something so hard.

I did actually try to implement what JamesCherill told me to do, but I have a really bad imagination. I couldn't imaging his code from text. What resulted from that was the if-else statements. A total failure. xD
I'm just a visual learner.

Anyways, I rather understand the code and get an F in the class than get a A in the class and not understand the code.

Thank you nick.crane.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.