Why does my program only provide change in dollar amounts? - java

This is my current code:
import java.util.Scanner;
public class CustomerChange {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double cost = 0.00;
double cash = 0.00;
double dollars = 0.00;
System.out.println("Price: ");
cost = scanner.nextDouble();
System.out.println("Cash: ");
cash = scanner.nextDouble();
if (cash < cost) {
System.out.println("Not enough cash. Goodbye.");
}
else if (cash > cost) {
dollars = cash - cost;
System.out.println("\nChange: \n");
if ((int) dollars / 20 > 0) {
System.out.println("Twenties: " + (int) dollars / 20);
dollars %= 20;
}
if ((int) dollars / 10 > 0) {
System.out.println("Tens: " + (int) dollars / 10);
dollars %= 10;
}
if ((int) dollars / 5 > 0) {
System.out.println("Fives: " + (int) dollars / 5);
dollars %= 5;
}
if ((int) dollars / 1 > 0) {
System.out.println("Ones: " + (int) dollars / 1);
dollars %= 1;
dollars *= 100;
}
if ((int) dollars / 25 > 0) {
System.out.println("Quarters: " + (int) dollars / 25);
dollars %= 25;
}
if ((int) dollars / 10 > 0) {
System.out.println("Dimes: " + (int) dollars / 10);
dollars %= 10;
}
if ((int) dollars / 5 > 0) {
System.out.println("Nickels: " + (int) dollars / 5);
}
if ((int) dollars / 1 > 0) {
System.out.println("Pennies: " + (int) dollars / 1);
}
} else if (cash == cost) {
System.out.println("Thank you. Goodbye.");
}
scanner.close();
}
}
Right now, when I enter in a price of 3.25 and a cash of 4, I don't get a return of my change, but when I enter in a price of 168.75 and a cash of 200, I get:
Price:
168.75
Cash:
200
Change:
Twenties: 1
Tens: 1
Ones: 1
Quarters: 1
Where am I going wrong? It took forever to figure out the math and I thought that was the crux but I guess not?

When you are inputting: Price: 3.25 and Cash: 4
(int)(0.75) will be 0.
So it will not get inside any of the if block.
Put a condition like
if ((int) dollars / 1 == 0) {
System.out.println("Pennies: " + (int)(dollars*100));
}
Then it will definitely work.

Your code is overly complicated due to attempting to work with double instead of just converting everything to an integer to begin with. This way everything is in the value of pennies, and you do not need to worry about any casting or multiplying a decimal later on by 100 in order to work with the coins, and the code will be less prone to bugs.
Here is what it would look like using similar logic you were using, but instead if in the form of pennies (you don't even need the if statements):
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pricePennies = 0;
int cashPennies = 0;
System.out.println("Price: ");
pricePennies = (int) (scanner.nextDouble() * 100);
System.out.println("Cash: ");
cashPennies = (int) (scanner.nextDouble() * 100);
if (cashPennies < pricePennies) {
System.out.println("Not enough cash. Goodbye.");
}
else if (cashPennies > pricePennies) {
int change = cashPennies - pricePennies;
System.out.println("Twenties: " + change / 2000);
change %= 2000;
System.out.println("Tens: " + change / 1000);
change %= 1000;
System.out.println("Fives: " + change / 500);
change %= 500;
System.out.println("Ones: " + change / 100);
change %= 100;
System.out.println("Quarters: " + change / 25);
change %= 25;
System.out.println("Dimes: " + change / 10);
change %= 10;
System.out.println("Nickels: " + change / 5);
change %= 5;
System.out.println("Pennies: " + change / 1);
change %= 1;
}
else if (cashPennies == pricePennies) {
System.out.println("Thank you. Goodbye.");
}
scanner.close();
}
Test Runs:
Price:
168.75
Cash:
200
Twenties: 1
Tens: 1
Fives: 0
Ones: 1
Quarters: 1
Dimes: 0
Nickels: 0
Pennies: 0
Price:
3.25
Cash:
4
Twenties: 0
Tens: 0
Fives: 0
Ones: 0
Quarters: 3
Dimes: 0
Nickels: 0
Pennies: 0
Price:
54748
Cash:
63939.46
Twenties: 459
Tens: 1
Fives: 0
Ones: 1
Quarters: 1
Dimes: 2
Nickels: 0
Pennies: 1

Related

Trouble with the converting units

I am having a hard time understanding how to convert amounts such as $1.17 into this output:
1 dollar,
1 dime,
1 nickel,
2 pennies.
I need to use if statements which I can figure out but, the problem i am having is trying to get the change amounts to display correctly. Here is my code. I`m a visual learner so if you start me in the right direction that would be helpful.
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int Dollars = (int) (number);
int Quarters = Dollars / 25;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)Dollars + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print( Quarters + " Quarters ");
}
}
You will probably want to use the modulus operator %. It is used with 2 numbers and returns the remainder of a divided by b where a is the left hand assignment and b is the right hand represented like a%b.
Example:
11%2=1 explanation: 5*2 = 10, 11-10 = 1
.66%.25=.16 explanation: 2*.25 = .5, .66-.5=.16
Start with a simple problem where you only have 2 types of coins, say 8ยข or $0.08.
double monies = .08;
int numNickles = (int)(monies/.05) = 1 // one nickle
monies = monies % .05; // or you can write as monies %=.05;
// monies value should now be .03
int numPennies = (int)(monies/.01) = 3 // three pennies
A much simpler approach than using modulus is to calculate the units of measurement in top-down fashion (from the highest to the lowest) and keep deducting them from the total already converted into the lowest unit.
A lot of libraries use this approach with units of time as well i.e. converting a time span into hours, minutes and seconds. Here's the same approach for currency. I've added inline comments to explain the code as best as possible.
// Scan the amount
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount: ");
double amount = scanner.nextDouble();
scanner.close();
// convert into cents
int cents = (int) (amount * 100);
// get dollars
int dollars = cents/100;
// cents left after dollars
cents = cents - dollars*100;
// get quarters
int quaters = cents/25;
// cents left after quarters
cents = cents - quaters*25;
// get dimes
int dimes = cents/10;
// cents left after dimes
cents = cents - dimes*10;
// get nickels
int nickels = cents/5;
// cents left after nickels
cents = cents - nickels*5;
// leftover cents are pennies
int pennies = cents;
Now, just build the output message with a StringBuilder as
StringBuilder msg = new StringBuilder("You have:");
if (dollars > 0) {
msg.append(" ").append(dollars).append(" dollar").append(dollars > 1 ? "s" : "");
}
if (quaters > 0) {
msg.append(" ").append(quaters).append(" quarter").append(quaters > 1 ? "s" : "");
}
if (dimes > 0) {
msg.append(" ").append(dimes).append(" dime").append(dimes > 1 ? "s" : "");
}
if (nickels > 0) {
msg.append(" ").append(nickels).append(" nickel").append(nickels > 1 ? "s" : "");
}
if (pennies > 0) {
msg.append(" ").append(pennies).append(" pennie").append(pennies > 1 ? "s" : "");
}
System.out.println(msg);
Output :
Enter amount: 1.17
You have: 1 dollar 1 dime 1 nickel 2 pennies
Enter amount: 12.99
You have: 12 dollars 3 quarters 2 dimes 4 pennies

Convertiny Monetary Units

I got the dollars to work but now I can`t figure out how to display the quarters, dimes, nickels, and pennies correctly. Technically they show up but my professor wants $1.35 to show up as 1 dollar 1 quarter and 1 dime. But, mine shows up as 1 dollars 5 Quarters 13 Dimes 27 Nickels 135 Pennies. Here is my code:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an amount in double, for example 11.56: " );
double number = input.nextDouble();
System.out.println("Your amount " + number + " consists of ");
int remainingamount = (int)(number*100);
int Quarters = remainingamount/25;
int Dimes = remainingamount/10;
int Nickels = remainingamount/5;
int Pennies = remainingamount;
if (number == 1) {
System.out.print("1 dollar ");
}
else if (number > 1) {
System.out.print((int)number + " dollars ");
}
if (number == 0) {
System.out.println("");
}
System.out.print(Quarters + " Quarters " + Dimes + " Dimes " + Nickels + " Nickels " + Pennies + " Pennies");
}
}
For each different coin you calculate, you need to remove this from the remaining amount. Such as (untested):
int Dollars = (int)number;
int remainingamount = (int)((number-Dollars)*100);
int Quarters = remainingamount/25;
remainingamount -= Quaters * 25;
int Dimes = remainingamount/10;
remainingamount -= Dimes * 10
int Nickels = remainingamount/5;
remainingamount -= Nickels * 5
int Pennies = remainingamount;
Since you're using Java, have you tried JSR 354?
See JavaMoney.org or the JSR 354 Detail page at JCP.org It offers standard API for the conversion of monetary units and default exchange rate providers by the IMF or European Central Bank.

How do I properly return money double variable in Java

I'm currently working on an assignment for school where I need to write a program that it needs to return your change in this mode
Input:
purchaseAmount: $12.45
givenAmount: $15.00
Output:
Change: $2.55
2 one dollar bills
2 quarters
1 nickel
But, if I work with this case scenario it works fine. Now, If I want this scenario to work this what I get
Input:
purchaseAmount: $19.51
givenAmount: $50.01
Output:
Twenty dollar bill 1
Ten dollar bill: 1
Quarters: 1
Dimes: 2
Pennies: 4
Which is incorrect since I'm returning to the costumer 30.49 instead of 30.5
Can't figure out whats the issue here.
Thanks
boolean isFiveBillOn = false, isTwentybillOn = false, isTenbillOn = false, isDollarOn = false, isQuartersOn = false, isDimesOn = false, isNicklesOn = false, isPenniesOn = false;
//retrieve amount due
String moneyd = JOptionPane.showInputDialog("Enter the amount due");
double amountd = Double.parseDouble(moneyd);
String moneyr = JOptionPane.showInputDialog("Enter amount you would like to pay");
double amountr = Double.parseDouble(moneyr);
//calculate difference
double difference = (amountr - amountd);
//convert to pennies
int balance = (int)(difference * 100);
//twenty dollar bill
int twentydollars = balance / 2000;
balance = (balance % 2000);
if (twentydollars > 0) {
isTwentybillOn = true;
}
//ten dollar bill
int tendollars = balance / 1000;
balance = (balance % 1000);
if (tendollars > 0) {
isTenbillOn = true;
}
//five dollar bill
int fivedollars = balance / 500;
balance = (balance % 500);
if (fivedollars > 0) {
isFiveBillOn = true;
}
//dollar bill
int dollars = balance / 100;
balance = (balance % 100);
if (dollars > 0) {
isDollarOn = true;
}
//quartes
int quarters = balance / 25;
balance = (balance % 25);
if (quarters > 0) {
isQuartersOn = true;
}
//dimes
int dimes = balance / 10;
balance = (balance % 10);
if (dimes > 0) {
isDimesOn = true;
}
//nickles
int nickles = balance / 5;
balance = (balance % 5);
if (nickles > 0){
isNicklesOn = true;
}
//pennies
int pennies = balance / 1;
balance = (balance % 1);
if (pennies > 0){
isPenniesOn = true;
}
//checking for difference over 0
if (difference < 0) {
JOptionPane.showMessageDialog(null, "The amount received can't be less than the amount owned");
} else {
// Returning Message
} if (isTwentybillOn) {
System.out.println("Twenty dollar bill " + twentydollars);
} if (isTenbillOn) {
System.out.println("Ten dollar bill: " + tendollars);
} if (isDollarOn) {
System.out.println("One Dollar Bill: " + dollars);
} if (isQuartersOn) {
System.out.println("Quarters: " + quarters);
} if (isDimesOn) {
System.out.println("Dimes: " + dimes);
} if (isNicklesOn) {
System.out.println("Nickles: " + nickles);
} if (isPenniesOn) {
System.out.println("Pennies: " + pennies);
} else {
System.out.println("Thanks! have a good day");
}
}
You should never use a double or any other floating-point data type to represent money. The reason is that they can't represent all values exactly. For example, the following line:
System.out.println(new BigDecimal(0.1));
prints
0.1000000000000000055511151231257827021181583404541015625
For a longer explanation why, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.
I suggest using BigDecimal instead.
An alternative if you only want to use primitives is to use an int to store the currency value in cents instead, and divide by 100 when displaying the value.

Odd accuracy error Java

Currently I am attempting to write a change machine in java. For some reason there is a large loss in accuracy during conversion.
It will first ask for the data values of how much is owed and how much is paid. Then it will divide out the numbers of quarters and mod out the remainder. Then it will perform this with dimes, nickles, and then pennies. After this it will then print out how much change is owed.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class change{
public static void main (String str[]) throws IOException {
//asker thingy
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Cost of the Item:");
System.out.print("$");
double costowed = scan.nextDouble();
System.out.println("Please Enter the Amount Payed:");
System.out.print("$");
double costpayed = scan.nextDouble();
//Quarters
double a1 = Math.round( (costpayed - costowed) * 100);
int quarters = (int)(a1 / 25);
int a2 = (int)(a1 % 25);
//dimes
int dimes = (int)(a2 / 10);
int a3 = (int)(a1 % 10);
//nickles & pennies
int nickles = (int)(a3 / 5);
int pennies = (int)(a1 % 5);
//change owed
double arc = (double)(a1 / 100);
//print sequence
System.out.println("Change owed: " + arc);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickles: " + nickles);
System.out.println("Pennies: " + pennies);
}
}
The line
int a3 = (int)(a1 % 10);
should be:
int a3 = (int)(a2 % 10);
And likewise int pennies = (int)(a1 % 5); should be int pennies = (int)(a3 % 5);.

min change greedy algorithm in java

Ok so i need to make a program to ask me for an amount of money, then I need it to tell me the least amount of coins to make it. The coins I can use are: dollars, quarters, dimes, nickels, and pennies. For example, When I run the program it's supposed to look like this:
> run Coins
Enter the amount of given money:
[1.73]
Give the seller 8 coins:
1 dollars,
2 quarters,
2 dime,
0 nickels,
3 pennies.
This is What I have so far:
import java.util.Scanner;
class Coins {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
double money;
System.out.println("Enter the amount of money ");
money = input.nextDouble();
while (money > 0.0 ){
if (money >= 1) {
System.out.println(money/1+"dollars");
money -= 1;
}
else if (money>=.25) {
System.out.println(money/.25+"quarters");
money-=.25;
}
else if (money>=.10) {
System.out.println(money/.10+"Dimes");
money-=.10;
}
else if (money>=.05) {
System.out.println(money/.05+"Nickels");
money-=.05;
}
else if (money>=.01) {
System.out.println(money/.01+"Penny");
money-=.01;
}
}
}
}
The part I need help with is this: If I run the program and enter the amount 1.73, the way I have the code written, it takes the number 1.73, divides it by 1, and prints "1.73 dollars". I need a way to get rid of the decimal part so instead of printing "1.73 dollars", it prints "1 dollar". But I'm not sure how to do this. I tried converting it to an int but it messes up the flow of the other statements. Please help me.
You should use the combination of floor with casting to double, the following code works:
class Coins {
public static void main (String args[]) {
double money = 1.73;
while (money > 0.0 ){
if (money >= 1) {
System.out.println(Math.floor(money/1)+" dollars");
money -= Math.floor(money/1)*(double)1;
}
else if (money>=.25) {
System.out.println(Math.floor(money/.25)+" quarters");
money-=Math.floor(money/.25)*(double).25;
}
else if (money>=.10) {
System.out.println(Math.floor(money/.10)+" Dimes");
money-=Math.floor(money/.10)*(double).10;
}
else if (money>=.05) {
System.out.println(Math.floor(money/.05)+" Nickels");
money-=Math.floor(money/.05)*(double).05;
}
else if (money>=.01) {
System.out.println(Math.round(money/.01)+" Penny");
money-=Math.round(money/.01)*(double).01;
}
}
}
}
Another bug you had:
You should subtract Math.floor(money/XXX)*(double)XXX not (double)XXX
You need get rid of the remainder after the divisions. You can use Math.floor() for this:
class Coins {
public static void main (String args[]) {
double money = 1.73;
int dollars = (int) Math.floor(money/1);
money -= dollars * 1;
int quarters = (int) Math.floor(money/0.25);
money -= quarters * 0.25;
int dimes = (int) Math.floor(money/0.10);
money -= dimes * 0.10;
int nickels = (int) Math.floor(money/0.05);
money -= nickels * 0.05;
int pennies = (int) Math.round(money * 100);
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);
}
}
Resulting in:
Dollars: 1
Quarters: 2
Dimes: 2
Nickels: 0
Pennies: 3

Categories