Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package exceptiondemo;
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class Change {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- double paid, toCharge;
- try {
- System.out.print("Enter amount paid by the customer: GBP");
- paid = scan.nextDouble();
- System.out.print("Enter amount to charge the customer: GBP");
- toCharge = scan.nextDouble();
- int[] coinCount = getChange(paid, toCharge);
- System.out.print("Custom has to be returned:");
- for (int i = 0; i < validChange.length; i++) {
- if (coinCount[i] == 0) {
- continue;
- }
- System.out.print(" " + coinCount[i] + " * " + validChange[i] + "p");
- }
- } catch (InputMismatchException e) {
- System.out.println("Entered values are not valid");
- } catch (PaidLessThanToChargeException e) {
- System.out.println("Paid amount by the customer is less than the amount to charge");
- }
- }
- /**
- * Valid change in penny
- */
- protected static double[] validChange = {75, 15, 3, 1, 0.5, 0.25};
- /**
- * @param paid Amount paid by the customer
- * @param toCharge Actual amount to charge
- * @return Number of coins with respect to validChange
- */
- protected static int[] getChange(double paid, double toCharge) throws PaidLessThanToChargeException {
- if (paid - toCharge < 0.0001) {
- throw new PaidLessThanToChargeException();
- }
- double change = (paid - toCharge) * 100;
- int[] coinCount = new int[validChange.length];
- for (int i = 0; i < validChange.length; i++) {
- coinCount[i] = (int) (change / validChange[i]);
- change = change % validChange[i];
- }
- return coinCount;
- }
- }
- class PaidLessThanToChargeException extends Exception {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement