Pin It

How to count monetary units through a Java program ?.

Program to demonstrate how to count monetary units through a Java program.

import java.util.Scanner;

public class MonetaryUnits {

 public static void main(String[] args) {

  // Creating a Scanner object using a constructor
  // which takes the System.in object. There are various
  // constructors for Scanner class for different
  // purposes. We want to use Scanner class to read
  // data from console on the system, So we are using
  // a constructor which is taking an System.in object
  Scanner scanner = new Scanner(System.in);

  // Prompt the user to enter amount in dollars (in decimals)
  System.out.print("Enter an amount in dollars (in decimals) : ");
  double amount = scanner.nextDouble();

  // Convert the amount into cents by multiplying it by 100.
  int amountLeft = (int)(amount * 100);

  // In order to find number of dollars divide amountLeft
  // by 100.
  int dollars = amountLeft / 100;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 100).
  amountLeft = amountLeft % 100;

  // In order to find number of quarters divide amountLeft
  // by 25. 
  int quarters = amountLeft / 25;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 25).
  amountLeft = amountLeft % 25;

  // In order to find number of dimes divide amountLeft
  // by 10.
  int dimes = amountLeft / 10;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 10).
  amountLeft = amountLeft % 10;

  // In order to find number of dimes divide amountLeft
  // by 5.
  int nickels = amountLeft / 5;

  // take leftover amount by taking the remainder of amountLeft
  // (modulus by 5).
  amountLeft = amountLeft % 5;

  // In order to find number of pennies divide amountLeft
  // by 1.
  int pennies = amountLeft / 1;

  // Displaying the result on the console.
  System.out.println("The amount : " + amount + " consists of");
  System.out.println(dollars + " Dollars");
  System.out.println(quarters + " Quarters");        
  System.out.println(dimes + " Dimes");
  System.out.println(nickels + " Nickels");
  System.out.println(pennies + " Pennies");

 }

}



Output of the program : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot