Jump to content

I have most of the program done, just that I need it to print out the individual coins for example, quarters x 3, pennies x 1. Instead of just 4 coins for 76 cents. Also don't know if format is right.

 

import java.util.Scanner;
public class Money
{
    public static void main(String args[])
    {
        int[] coins = { 1, 5, 10, 25};
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter Change (In Cents): ");
        int sum = scan.nextInt();
        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        String quarter = "";
        Money minCoin = new Money();
        System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
        System.out.println(counter4);
    }

    private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4)
    {
        if (sum <= 0 || coins.length == 0)
        {
            return 0;
        }

        for (int i = coins.length - 1; i >= 0; i--)
        {
            if(coins == 1 && coins != 5)
            {
                counter1++;
            }

            if(coins == 5)
            {
                counter2++;
            }

            if(coins == 10)
            {
                counter3++;
            }

            if(coins == 25)
            {
                counter4++;
            }

            if (coins <= sum)
            {
                System.out.println("Pennies: " + counter1);
                System.out.println("Nickels: " + counter2);
                System.out.println("Dimes: " + counter3);
                System.out.println("Quarters: " + counter4);
                return 1 + findMinCoins(coins, sum - coins, counter1, counter2, counter3, counter4);

            }
        }
        return 0;
    }

}

Link to comment
https://linustechtips.com/topic/699014-need-help-with-make-change-program/
Share on other sites

Link to post
Share on other sites

Try inverting the coin values in the array, from largest to smallest

Here's the code in php

 

<?php

$coin_values = array(25,10,5,1);
$coin_names = array('quarters','dimes','nickels','pennies');
$coin_count = 4;
$coins = array(0,0,0,0);

$change = 76;

$coin_active = 0;
while (($change > 0) && ($coin_active<$coin_count)) { 
 while ($change >= $coin_values[$coin_active]) { 
  $change = $change - $coin_values[$coin_active];
  $coins[$coin_active]++;
 }
 $coin_active++;
}
echo 'Your change is : '; 
foreach ($coins as $index=>$value) { 
  if ($value!=0) echo $value . ' ' . $coin_names[$index] . ' ';
}
echo '.';
?>

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×