From ef09ab26ce9b19031db21a5c049279412166ae56 Mon Sep 17 00:00:00 2001 From: Logen Kain Date: Wed, 20 Jan 2021 08:08:58 -0500 Subject: [PATCH] Add moneyChange --- exact-change/moneyChange.java | 92 +++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 exact-change/moneyChange.java diff --git a/exact-change/moneyChange.java b/exact-change/moneyChange.java new file mode 100644 index 0000000..f50e124 --- /dev/null +++ b/exact-change/moneyChange.java @@ -0,0 +1,92 @@ +import java.util.Scanner; +/* + * total change as input + * output fewest coins, one type per line + * dollars,quarters,dimes,nickels,pennies + * + * use singular and plural coin names as appropriate + * + * input: 0 + * output: no change + * + * input:45 + * output: + * 1 quarter + * 2 dimes + * + * + * Must define method: + * Positions 0-4 of coinVals should contain: + * + * the number of dollars,quarters,dimes,nickels, and pennies + * public static void exactChange(int userTotal, int[] coinVals) + */ + +public class moneyChange{ + + public static String detPlural(int numCoins, + String single, String plural){ + String word; + if (numCoins == 1){ + word = single; + } + else{ + word = plural; + } + + return word; + } + + public static void exactChange(int userTotal, int[] coinVals){ + int runningTotal = userTotal; + String[] changeTypes = new String[5]; + + //dollars + coinVals[0] = runningTotal/100; + runningTotal %=100; + changeTypes[0] = detPlural(coinVals[0], "dollar", "dollars"); + + //quarters + coinVals[1] = runningTotal/25; + runningTotal %=25; + changeTypes[1] = detPlural(coinVals[1], "quarter", "quarters"); + + //dimes + coinVals[2] = runningTotal/10; + runningTotal %=10; + changeTypes[2] = detPlural(coinVals[2], "dime", "dimes"); + + //nickels + coinVals[3] = runningTotal/5; + runningTotal %=5; + // I recon I could never have more than one nickel, but + // may as well be consistant. + changeTypes[3] = detPlural(coinVals[3], "nickel", "nickels"); + + //pennies + coinVals[4] = runningTotal; + changeTypes[4] = detPlural(coinVals[4], "penny", "pennies"); + + for (int i = 0; i 0){ + System.out.println(coinVals[i] + " " + changeTypes[i]); + } + } + } + + public static void main(String[] args) { + Scanner scnr = new Scanner(System.in); + + final int userTotal = scnr.nextInt(); + int[] coinVals = new int[5]; + + if (userTotal <= 0){ + System.out.println("no change"); + scnr.close(); + return; + } + + exactChange(userTotal, coinVals); + scnr.close(); + } +}