converting money into all possible combinations - java

I know my question is repeated but I still couldn't understand what the other answers are explaining. Below is my code and I have calculated it to get to the first line which is 57 pennies + 0 dimes + 0 nickels + 0 quarters and I am thinking to run a loop that will list all the possible combinations of pennies, dimes, nickels, quarters. But, I don't know how.
public class Conversion{
public static void main(String[] args) {
int cents = 57;
int quarter = 25;
int dime = 10;
int nickel = 5;
int penny = 1;
int totalPennies = cents / penny;
cents %= penny;
int totalNickels = cents / nickel;
cents %= nickel;
int totalDimes = cents / dime;
cents %= dime;
int totalQuarters = cents / quarter;
cents %= quarter;
System.out.print(totalPennies + " pennies + ");
System.out.print(totalNickels + " nickels + ");
System.out.print(totalDimes + " dimes + ");
System.out.println(totalQuarters + " quarters");
}
}

Your order of operations is backwards.
The first thing you do is count how many pennies you have. Since pennies are literally valued at 1, you can have 57 pennies and make up $0.57 just fine. That is obviously not what you want to accomplish.
What you want to do is count from your highest denomination and work your way backwards. Here's a sample.
// This should be the first operation
int totalQuarters = cents / quarter;
cents %= quarter;
I leave reordering the rest as an exercise for the reader, but the output then becomes correct once successfully reordered.
2 pennies + 1 nickels + 0 dimes + 2 quarters

Related

java code to convert cents into dimes, nickels

System.out.print("Enter the AMOUNT in CENTS: ");
int cents = scan.nextInt();
scan.close();
int dimes = (cents % 25)/10;
System.out.println("Dimes is " +dimes);
int nickels = ((cents % 25) %10) /5;
System.out.println("Nickels is " +nickels);
int pennies = ((cents % 25) %10) %5;
System.out.println("Pennies is " +pennies);
I can't seem to convert the cents into dimes, nickels, and pennies. the output should be like this:
Enter AMOUNT in CENTS : 28
Dimes is 2
Nickels is 1
Pennies is 3
but the output of my program is showing is:
Enter the AMOUNT in CENTS: 28
Enter the AMOUNT in CENTS: 28
Dimes is 0
Nickels is 0
Pennies is 3
can someone help me with the formula?
Try this:
int dimes = cents / 10;
System.out.println("Dimes is " +dimes);
int nickels = (cents % 10) / 5;
System.out.println("Nickels is " +nickels);
int pennies = (cents % 10) % 5;
System.out.println("Pennies is " +pennies);
A dime is 10 cents. A nickel is 5 cents. A penny is 1 cent.

Java Coin Change Evaluation

I am currently writing a program that prints only the coins used when returning change. However, I get 2 assertions errors which are evaluated on the server's back-end. There are no sample test values, you have to make up your own.
expected:[... Change Due $0.01 [1 penny] ]
but was:[... Change Due $0.01 [2 pennies] ]
expected:[... Change Due $0.19 [1 dime 1 nickel 4 pennies ]
but was:[... Change Due $0.19 [2 dimes ]
/**
* Calculate the amount of change based on user input.
* Output coins with an output greater than 0.
* #param args returns an argument array for string objects
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Total amount? ");
double total = input.nextDouble();
System.out.print("Cash payment? ");
double payment = input.nextDouble();
double changeDue = payment - total;
System.out.println();
System.out.printf("Change Due $%.2f\n\n", changeDue);
int cents = (int) Math.ceil(changeDue * 100);
int dollars = Math.round((int) cents / 100);
cents = cents % 100;
int quarters = Math.round((int) cents / 25);
cents = cents % 25;
int dimes = Math.round((int) cents / 10);
cents = cents % 10;
int nickels = Math.round((int) cents / 5);
cents = cents % 5;
int pennies = Math.round((int) cents / 1);
int[] coins = {dollars,quarters,dimes,nickels,pennies};
String[] names = {"dollar", "quarter", "dime", "nickel", "penny"};
for (int i = 0; i < 5; i++) {
if (coins[i] == 1) {
System.out.println(coins[i] + " " + names[i]);
} else if (coins[i] > 1 && i != 4) {
System.out.println(coins[i] + " " + names[i] + "s");
}
}
if (coins[4] > 1) {
System.out.println(coins[4] + " pennies");
}
}
Your code actually works fine. But the problem is if you just print your "changeDue" variable and see then you can see there is a 9 at the end. It is printed as 0.010000000000000009 not as 0.010000000000000000 as you would expect it to. Then it is ceiled as 2 after multiplying by 100. Then you get 2 pennies as the answer.
Actually this seems to be a problem with how decimals are stored. (Java Double value = 0.01 changes to 0.009999999999999787) It is explained here nicely. So you might have to change your approach a little bit.
You have made a fairly common mistake in Java. Money cannot be represented by double, they are different things. In Java the closest thing we have to money is called BigDecimal. It's a little more awkward because you can't use arithmetic symbols with it (+-/*^%), but it's a lot more accurate.
There is also a formal specification for money: Money and Currency API (JSR 354), for which there are a couple of implementations including Joda Money and the offical reference implementation.

How to display correct amount of change?

I am pretty new to java and am trying to create a simple program that converts an amount of money into change. However, I find that the program always prints one penny less than necessary.
I would have just added 1 to my pennies variable before printing but this would mean that when change is 0, it would still add a penny as change.
Here is my code:
change = amtPaid-Math.round((total*1.13)*100)/100.0;
pennies = (int) (change * 100);
twenties = (int)(pennies/2000);
pennies %= 2000;
tens = (int)(pennies/1000);
pennies %= 1000;
fives = (int)(pennies/500);
pennies %= 500;
toonies = (int)(pennies/200);
pennies %= 200;
loonies = (int)(pennies/100);
pennies %= 100;
quarters = (int)(pennies/25);
pennies %= 25;
dimes = (int)(pennies/10);
pennies %= 10;
nickels = (int)(pennies/5);
pennies %= 5;
I get this output after providing sample input:
The change will be: 1.83
To make up this amount, you will need:
0 twenty-dollar bills 0 ten-dollar bills
0 five-dollar bills 0 toonies
1 loonies 3 quarters
0 dimes 1 nickels
2 pennies
Does anyone know why this may be happening and how to fix it?
The way I see it, get your Grand Total (cost and taxes all in) to a decimal precision of no more than 2 (ie: 55.28). Don't allow the decimal precision to be more than 2. Whatever the rounding mechanism you use, make sure your happy with the final result.
Subtract the Amount Owed from the Amount Paid and make sure the final result is to a decimal precision of 2 (ie: 60.00 - 55.2814 = 4.7186 = 4.72 {rounded-up}). By not rounding properly to a decimal precision of 2 is where you can loose or gain a penny when calculating returned change.
Break the Amount To Return into Dollars and Cents. Both should be integer values (ie: 4 Dollars and 72 Cents).
// A value for the sake of this example. Taxes Included!
double totalOwed = 52.26534;
// Round to a precision of 2 (round UP on .5)
double grandTotal = BigDecimal.valueOf(totalOwed)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
// A value for the sake of this example.
double amountPaid = 60.00;
// Round to a precision of 2 (round UP on .5)
double returnValue = BigDecimal.valueOf(amountPaid - grandTotal)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
int dollars = Integer.parseInt(String.valueOf(returnValue).split("\\.")[0]);
int cents = Integer.parseInt(String.valueOf(returnValue).split("\\.")[1]);
Work out the bill currency to be returnd and add it to a List for display later. There are a LOT of different ways to do this. Here is one way:
List<String> change = new ArrayList<>();
int returnVal;
// Some displayable information
change.add("Total Cost: --> " + String.valueOf(grandTotal));
change.add("Total Paid: --> " + String.valueOf(amountPaid));
change.add("Return change: --> " + String.valueOf(returnValue));
// 100 Dollar Bills
if (dollars >= 100) {
returnVal = dollars / 100;
change.add(" " + String.valueOf(returnVal) + " Hundred Dollar Bill(s)");
dollars -= (returnVal * 100);
}
// 50 Dollar Bills
if (dollars >= 50) {
returnVal = dollars / 50;
change.add(" " + String.valueOf(returnVal) + " Fifty Dollar Bill(s)");
dollars -= (returnVal * 50);
}
// 20 Dollar Bills
if (dollars >= 20) {
returnVal = dollars / 20;
change.add(" " + String.valueOf(returnVal) + " Twenty Dollar Bill(s)");
dollars -= (returnVal * 20);
}
// 10 Dollar Bills
if (dollars >= 10) {
returnVal = dollars / 10;
change.add(" " + String.valueOf(returnVal) + " Ten Dollar Bill(s)");
dollars -= (returnVal * 10);
}
// 5 Dollar Bills
if (dollars >= 5) {
returnVal = dollars / 5;
change.add(" " + String.valueOf(returnVal) + " Five Dollar Bill(s)");
dollars -= (returnVal * 5);
}
// 2 Dollar Bills
if (dollars >= 2) {
returnVal = dollars / 2;
change.add(" " + String.valueOf(returnVal) + " Two Dollar Bill(s)");
dollars -= (returnVal * 2);
}
// 1 Dollar Bills
if (dollars >= 1) {
returnVal = dollars / 1;
change.add(" " + String.valueOf(returnVal) + " One Dollar Bill(s)");
dollars -= (returnVal * 1);
}
// Quarters (working against cents now)
if (cents >= 25) {
returnVal = cents / 25;
change.add(" " + String.valueOf(returnVal) + " Quarter(s)");
cents -= (returnVal * 25);
}
// Dimes
if (cents >= 10) {
returnVal = cents / 10;
change.add(" " + String.valueOf(returnVal) + " Dime(s)");
cents -= (returnVal * 10);
}
// Nickles
if (cents >= 5) {
returnVal = cents / 5;
change.add(" " + String.valueOf(returnVal) + " Nickle(s)");
cents -= (returnVal * 5);
}
// Pennies
if (cents >= 1) {
returnVal = cents / 1;
change.add(" " + String.valueOf(returnVal) + " Pennies");
cents -= (returnVal * 1);
}
// Display the Change-Back in Console Window
for (String str : change) {
System.out.println(str);
}
As you can see there is a lot of repetitious code in the example above. You can get rid of this by doing it yet another way. You can utilize an Array or Collection mechanism to hold the Dollar and coin denominations, for example:
// A value for the sake of this example. Taxes Included!
double totalOwed = 52.26534;
// Round to a precision of 2 (round UP on .5)
double grandTotal = BigDecimal.valueOf(totalOwed)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
// A value for the sake of this example.
double amountPaid = 60.00;
// Round to a precision of 2 (round UP on .5)
double returnValue = BigDecimal.valueOf(amountPaid - grandTotal)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
int dollars = Integer.parseInt(String.valueOf(returnValue).split("\\.")[0]);
int cents = Integer.parseInt(String.valueOf(returnValue).split("\\.")[1]);
List<String> change = new ArrayList<>();
int returnVal;
// Using arrays (or a collection mechanism) like this
// allows you to set whatever denominations you like.
String[][] dollarDenominations = {
{"100", " Hundred Dollar Bill(s)"},
{"50" , " Fifty Dollar Bill(s)" },
{"20" , " Twenty Dollar Bill(s)" },
{"10" , " Ten Dollar Bill(s)" },
{"5" , " Five Dollar Bill(s)" },
{"2" , " Two Dollar Bill(s)" },
{"1" , " One Dollar Bill(s)" }
};
// Although not commonly used, you might even want to
// add 50 cent pieces to the Array.
String[][] coinDenominations = {
{"25", " Quarter(s)"},
{"10", " Dime(s)" },
{"5" , " Nickle(s)" },
{"1" , " Pennies" }
};
// Some displayable information
change.add("Total Cost: --> " + String.valueOf(grandTotal));
change.add("Total Paid: --> " + String.valueOf(amountPaid));
change.add("Return change: --> " + String.valueOf(returnValue));
// Dollar Denominations
for (int i = 0; i < dollarDenominations.length; i++) {
int denom = Integer.parseInt(dollarDenominations[i][0]);
String typeString = dollarDenominations[i][1];
if (dollars >= denom) {
returnVal = dollars / denom;
change.add(" " + String.valueOf(returnVal) + typeString);
dollars -= (returnVal * denom);
}
}
// Coin Denominations
for (int i = 0; i < coinDenominations.length; i++) {
int denom = Integer.parseInt(coinDenominations[i][0]);
String typeString = coinDenominations[i][1];
if (cents >= denom) {
returnVal = cents / denom;
change.add(" " + String.valueOf(returnVal) + typeString);
cents -= (returnVal * denom);
}
}
// Display the Change-Back data in Console Window...
for (String str : change) {
System.out.println(str);
}
As said before, there are several other ways to do this sort of thing. The important thing is to work against Change-Back values that are to 2 decimal places. After all...to my knowledge, there is no such denomination as a one-sixth penny (there is no denomination for mills). The US at one time (between 1793 and 1857) use to have a half-Penny but that no longer exists and never ever will again for obvious reasons. In Canada there is no Penny since it costs almost 2 cents to make one and ultimately (in my opinion) the United States will most likely follow this scheme and save millions upon millions in the process since it also costs approx. 1.82+ cents to make a US penny.

Coin Math Conversion Issue

i'm currently coding a program that will convert pennies into the correct number of Twenties, tens, fives, dollars, quarters, dimes, nickels, and pennies. I've gotten the first part of the program correct but once i get to dollars my math is not outputting the correct amount. Any help?
import java.util.Scanner;
public class assignment1 {
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num, remainder;
System.out.print("Enter a value as a number of pennies: ");
num = inputReader.nextInt();
remainder = num % 2000;
System.out.println(num + " pennies is equal to:");
System.out.println((num / 2000) + " twenties");
System.out.println((remainder / 1000) + " tens");
System.out.println(((remainder % 1000) / 500) + " fives");
System.out.println((((remainder % 1000) % 500) / 100) + " dollars");
System.out.println(((((remainder % 1000) % 500) % 100) / 25) + " quarters");
System.out.println(((((remainder % 1000) % 500) % 100) % 25) / 10 + " dimes");
System.out.println((((((remainder % 1000) % 500) % 100) % 25) % 10) / 5 + " nickels");
System.out.println(((((((remainder % 1000) % 500) % 100) % 25) % 10) % 5) / 1 + " pennies");
}
}
Ok. I see what you've done. Let's start with
System.out.println((num / 2000) + "twenties");
System.out.println((remainder / 1000) + "tens");
System.out.println((remainder / 1000) % 500 + "fives");
System.out.println((((remainder / 1000) % 500) % 100) + "dollars");
The first line is correct. But you cannot use a simple remainder to keep a running tally. Also, num and remainder are terrible variable names. You can do something like this for a running tally,
System.out.print("Enter a value as a number of pennies: ");
int pennies = inputReader.nextInt();
System.out.println(pennies + " pennies is equal to:");
int twenties = pennies / 2000;
pennies -= twenties * 2000;
int tens = pennies / 1000;
pennies -= tens * 1000;
int fives = pennies / 500;
pennies -= fives * 500;
int dollars = pennies / 100;
pennies -= dollars * 100;
int quarters = pennies / 25;
pennies -= quarters * 25;
int dimes = pennies / 10;
pennies -= dimes * 10;
int nickels = pennies / 5;
pennies -= nickels * 5;
System.out.printf("%d twenties, %d tens, %d fives, %d dollars, "
+ "%d quarters, %d dimes, %d nickels, %d pennies%n", twenties,
tens, fives, dollars, quarters, dimes, nickels, pennies);
That would output (with 5869 as input),
5869 pennies is equal to:
2 twenties, 1 tens, 1 fives, 3 dollars, 2 quarters, 1 dimes, 1 nickels, 4 pennies
Or (if you wanted a non-running tally), just remove the subtractions from pennies like
System.out.println(pennies + " pennies is equal to:");
int twenties = pennies / 2000;
int tens = pennies / 1000;
int fives = pennies / 500;
int dollars = pennies / 100;
int quarters = pennies / 25;
int dimes = pennies / 10;
int nickels = pennies / 5;
System.out.printf("%d twenties, %d tens, %d fives, %d dollars, "
+ "%d quarters, %d dimes, %d nickels, %d pennies%n", twenties,
tens, fives, dollars, quarters, dimes, nickels, pennies);
And for 5869 you get
5869 pennies is equal to:
2 twenties, 5 tens, 11 fives, 58 dollars, 234 quarters, 586 dimes, 1173 nickels, 5869 pennies
This is possible with only mathematical operators. In most other programming task you'll encounter, you should use control structures to accomplish the steps in an algorithm.
Process
Begin with the number of pennies,
Divide by 2000 (the value of a $20-bill) and assign to a new variable,
Subtract from the number of pennies the value of the twenties,
Repeat for subsequent denominations ($10 bills, $5 bills, etc.)
I think the problem is that each time you divide your number it returns a new number as an Integer. So if you divide 100 pennies by 1000 it returns 0 so the rest of your math is going to return 0 no matter what you do.
example based on your code:
//assuming the input is 100 pennies the first remainder/1000 will equal to 0
System.out.println(((((((remainder / 1000) % 500) % 100) % 25) % 10) %5) % 1 + "pennies");
You haven't specified that you have to use modulus so i am assuming you're not.
Here's what i would do:
System.out.println(num + " pennies is equal to:");
System.out.println((num / 2000) + "twenties");
System.out.println((num / 1000) + "tens");
System.out.println((num / 500) + "fives");
System.out.println((num / 100) + "dollars");
System.out.println((num / 25) + "quarters");
System.out.println((num / 10) + "dimes");
System.out.println((num / 5) + "nickels");
System.out.println(num + "pennies");

Change Machine Math & Logic Errors

I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?

Categories

Resources