Advertisement
Guest User

change.java

a guest
Mar 6th, 2015
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. package exceptiondemo;
  2. import java.util.InputMismatchException;
  3. import java.util.Scanner;
  4.  
  5. public class Change {
  6.     public static void main(String[] args) {
  7.         Scanner scan = new Scanner(System.in);
  8.         double paid, toCharge;
  9.  
  10.         try {
  11.             System.out.print("Enter amount paid by the customer: GBP");
  12.             paid = scan.nextDouble();
  13.             System.out.print("Enter amount to charge the customer: GBP");
  14.             toCharge = scan.nextDouble();
  15.  
  16.             int[] coinCount = getChange(paid, toCharge);
  17.  
  18.             System.out.print("Custom has to be returned:");
  19.             for (int i = 0; i < validChange.length; i++) {
  20.                 if (coinCount[i] == 0) {
  21.                     continue;
  22.                 }
  23.  
  24.                 System.out.print(" " + coinCount[i] + " * " + validChange[i] + "p");
  25.             }
  26.         } catch (InputMismatchException e) {
  27.             System.out.println("Entered values are not valid");
  28.         } catch (PaidLessThanToChargeException e) {
  29.             System.out.println("Paid amount by the customer is less than the amount to charge");
  30.         }
  31.     }
  32.  
  33.     /**
  34.      * Valid change in penny
  35.      */
  36.     protected static double[] validChange = {75, 15, 3, 1, 0.5, 0.25};
  37.  
  38.     /**
  39.      * @param paid Amount paid by the customer
  40.      * @param toCharge Actual amount to charge
  41.      * @return Number of coins with respect to validChange
  42.      */
  43.     protected static int[] getChange(double paid, double toCharge) throws PaidLessThanToChargeException {
  44.         if (paid - toCharge < 0.0001) {
  45.             throw new PaidLessThanToChargeException();
  46.         }
  47.  
  48.         double change = (paid - toCharge) * 100;
  49.         int[] coinCount = new int[validChange.length];
  50.  
  51.         for (int i = 0; i < validChange.length; i++) {
  52.             coinCount[i] = (int) (change / validChange[i]);
  53.             change = change % validChange[i];
  54.         }
  55.  
  56.         return coinCount;
  57.     }
  58. }
  59.  
  60. class PaidLessThanToChargeException extends Exception {
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement