1

I tried making the Java money change program. Its goal is to tell you which denominations you should use as a change. Only thing you have to do is give the price of a thing and the money you "give". Right now the output is an array with a number of every denomination you have to "give back".

That's how the code looks:

    public class MyClass {
        static public int[] howManyCoins(double cost, double givenMoney)
        {
            double[] denominations = new double[] { 200, 100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01 };
        int[] coins = new int[15];

        double change = givenMoney - cost;

        for(double t: denominations)
        {
            int x = 0;
            if(change >= t)
            {
                 int numOfCoins = (int)(change/t);
                 change -= numOfCoins * t;
                 coins[x] = numOfCoins;

            }
            System.out.println(change);
            x++;
        }

        return coins;
    }
    public static void main(String args[]) {
        int[] returned = howManyCoins(276.73, 800);

        for(int t: returned){
            System.out.println(t);    
        }
    }
}

And thats how the output looks:

123.26999999999998
23.269999999999982
23.269999999999982
3.269999999999982
3.269999999999982
3.269999999999982
1.2699999999999818
0.2699999999999818
0.2699999999999818
0.0699999999999818
0.0699999999999818
0.019999999999981796
0.019999999999981796
0.009999999999981796
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0

At first the program prints a current change value, then a loop prints ever value from the returned array. First of all, all of the change values are really weird, they have all these numbers after the decimal point. Second of all as you can see the numbers in the returned array are not correct. This would be a correct output of this program (or what i want the output to be):

123.27
23.27
23.27
3.27
3.27
3.27
1.27
0.27
0.27
0.07
0.07
0.02
0.02
0.00
2
0
0
1
0
0
0
1
0
0
1
0
0
1
0
0
1
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
  • It's usually not a good idea to use fp for money. Convert the value to the lowest denomination as a integer: `276.73` --> `27673`. – 001 Aug 21 '19 at 14:25
  • 2
    You reinitialize `x` in each iteration. So only the first element of `coins` is ever changed. Either move `int x = 0` to above the for loop, or include the iterator in the for loop construct. – MC Emperor Aug 21 '19 at 14:34

0 Answers0