93 lines
2.0 KiB
Java
93 lines
2.0 KiB
Java
|
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<coinVals.length; i++){
|
||
|
if (coinVals[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();
|
||
|
}
|
||
|
}
|