Search Java Code Snippets

  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.

Java - Code Samples

 Sample 1. Write a Program for coin changer application. The program should set the cash box with available currency and then should render the exact change. If enough cash is not available , it should present the appropriate message.

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class CoinChanger {

enum Currency {

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>();

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());


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);


   Like      Feedback     coin changer application  coin changer app

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner