In: Computer Science
Java--
For this homework you are required to implement a change calculator that will provide the change in the least amount of bills/coins.
The application needs to start by asking the user about the purchase amount and the paid amount and then display the change as follows:
Supposing the purchase amount is $4.34 and the paid amount is $20, the change should be:
1 x $10 bill
1 x $5 bill
2 x Quarter coin
1 x Dime coin
1 x Nickle coin
1 x Penny coin
Note that the $20 and the $1 bills are not printed because the change did not require them, meaning that you do not print a bill unless the amount to be provided from that bill is larger than zero.
Hint: as discussed in class, you will need to cast from double to integer and this is how we did it in class:
int amount = (int)(scn.nextDouble()*100); // converting form dollars to cents by multiplying by 100
Assumption : Available denominations for giving change are $20 , $10 , $5 , $1 , Quarter Coins , Dime Coins , Nickle Coins and Penny coins.
It is a greedy approach where we always try to give the change of largest possible denomination. The approach repeats until the remaining amount becomes zero. For an easier implementation , everything should be converted into cents.
Hence , $20 = 2000 cents , $10 = 1000 cents , $5 = 500 cents , $1 = 100 cents , Quarter = 25 cents , Dime = 10 cents , Nickle = 5 cents and Penny = 1 cent.
Here is the complete working code using the above conversions.
import java.util.*;
public class Change
{
public static void main(String []args)
{
/* Purchase and Paid are values in terms of cents */
int purchase , paid;
Scanner sc = new Scanner(System.in);
/* Type casting and then multiplying dollars by 100 */
System.out.println("Enter Purchase Amount");
purchase = (int)(sc.nextDouble()*100);
/* Type casting and then multiplying dollars by 100 */
System.out.println("Enter Paid Amount");
paid = (int)(sc.nextDouble()*100);
/*Decreasing order of denominations is Cents */
int arr[] = {2000 , 1000 , 500 , 100 , 25 , 10 , 5 , 1};
/* Decreasing order of denominations in Dollars */
String denominations[] = {"$20 bill" ,"$10 bill" ,"$5 bill" , "$1 bill" ,
"Quarter Coin" , "Dime Coin " , "Nickle Coin" , "Penny Coin"};
/* rem is the amount to be paid back in terms of cents */
int i = 0 , rem = paid - purchase;
while(rem>0)
{
int denomination = arr[i];
/* How many denominations of ith type can be given*/
int howMany = rem/denomination;
/* update remaining cents*/
rem = rem%denomination;
/* If a type of denomination can be given */
if(howMany>0)
System.out.println(howMany + " X " + denominations[i]);
i++;
}
}
}
Here is the output to sample output to given input