import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class CoinChanger {
enum Currency {
DOLLAR(1),QUARTER(.25),DIME(.10),NICKEL(.05),PENNY(.01);
private double currencyValue;
Currency(double value){
currencyValue = value;
}
double getCurrencyValue(){
return this.currencyValue;
}
}
private static Map<Currency, Integer> cashBox;
private static Map<Currency, Integer> change;
static {
cashBox = new TreeMap<Currency, Integer>();
change = new TreeMap<Currency, Integer>();
initializeCashBox();
}
public static void main(String[] args) {
double amountToReturn = 18.79f; // Set the amount to be changed here
for(Entry<Currency, Integer> entry:cashBox.entrySet()){
Currency currency = (Currency)entry.getKey();
int coinCount = (int)(amountToReturn/(entry.getKey().getCurrencyValue()));
int availableCurrency = (int)(entry.getValue());
if(coinCount > availableCurrency){
coinCount = availableCurrency;
}
change.put(currency, coinCount);
if(coinCount > 0){
amountToReturn = amountToReturn - (coinCount * entry.getKey().getCurrencyValue());
}
}
System.out.println(change);
if(amountToReturn > .1){
System.out.println("Not enough cash");
}
}
private static void initializeCashBox(){
//set the cash box
cashBox.put(Currency.DOLLAR, 50);
cashBox.put(Currency.QUARTER, 0);
cashBox.put(Currency.DIME, 50);
cashBox.put(Currency.NICKEL, 50);
cashBox.put(Currency.PENNY, 50);
}
}
|
Map<String,String> treemap = new TreeMap();
treemap.put("United States", "Washington");
treemap.put("Canada", "Ottawa");
treemap.put("Canada", "Ottawa");
treemap.put("South Africa", "Pretoria");
treemap.put("South Africa", "Cape Town");
treemap.put("South Africa", "Bloemfontein");
System.out.println(treemap); // Duplicate Not allowed as it's a Map, Ordered by Keys as it's a TreeMap
|