Why is the last dollar change calculation wrong [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Why is the last calculation printing out the wrong calculation.
here is my code:
System.out.print("Enter total cost: ");
double totalCost = input.nextDouble();
System.out.print("The Customer has paid: ");
double customerAmount = input.nextDouble();
//Calculations
double changeOwed = customerAmount - totalCost;
System.out.println("Change owed: $"+(int)changeOwed);
int amountFifty = (int)changeOwed/50;
System.out.println("How many $50 notes = " +amountFifty);
int takeAway = (int)changeOwed - (amountFifty * 50);
int amount20 = takeAway / 20;
System.out.println("How many $20 notes = " +amount20);
int amount10 = (takeAway - amount20*20) / 10;
System.out.println("How many $10 notes = " +amount10);
enter code here
int amount5 = (takeAway - amount10*10) / 5;
System.out.println("How many $5 notes = " +amount5);
int amount2 = (takeAway - amount5*5) / 2;
System.out.println("How many $2 notes = " +amount2);
int amount1 = (takeAway - amount2*2) /1;
System.out.printl
n("How many $1 notes = " +amount1);

You are not keeping track of the change you have issued along the way correctly.
int takeAway = (int)changeOwed - (amountFifty * 50);
The line above correctly calculates what's left after you determine the number of $50 bills required. This means that:
int amount20 = takeAway / 20;
int amount10 = (takeAway - amount20*20) / 10;
correctly calculates the number of $10 and $20 bills.
int amount5 = (takeAway - amount10*10) / 5;
is incorrect because you do do not subtract the values of the $20 bills, only the $10 bills. You make a similar error calculating the $2, ie. you do not account for $20 and $10. The error compounds for the $1.
You could try something like:
int amountFifty = changeOwed / 50;
double takeAway = changeOwed - (amountFifty * 50);
int amount20 = takeAway / 20;
takeAway -= (amount20 * 20);
int amount10 = takeAway / 10;
takeAway -= (amount10 * 10);
int amount5 = takeAway / 5;
takeAway -= (amount5 * 5);
int amount2 = takeAway / 2;
takeAway -= (amount2 * 2);
int amount1 = takeAway / 1;

Related

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Java Calculating salary

I am clocking start and stop for workingtime, hh:mm.
Salary is 150 / hour.
I get the indata:
hour1 = keyboard.nextInt();
minute1 = keyboard.nextInt();
keyboard.nextLine();
hour2 = keyboard.nextInt();
minute2 = keyboard.nextInt();
Total hours:
totHours = hour2 - hour1;
Total minutes:
totMinutes = (minute2 + minute1)/60;
totTime = totHours + totMinutes;
totSalary = totTime*Salary;
It doesnt work. The result just counts the differens between hour2 and hour1 and ignores the minutes.
It seems like your hours and minutes are of type int; at least you are using nextInt to get the values, and I can reproduce your problem that way.
int hour1 = 12;
int minute1 = 45;
int hour2 = 14;
int minute2 = 30;
double totHours = hour2 - hour1;
double totMinutes = (minute2 + minute1)/60; // 1.0
double totTime = totHours + totMinutes; // 3.0
This is because if both the dividend and the divisor are integers, then / will also produce an integer, i.e. the floor of the actual division. Divide by 60.0, then it works. Also, use -, not +. And of course make sure to store the result in a double.
double totMinutes = (minute2 - minute1)/60.0; // -0.25
double totTime = totHours + totMinutes; // 1.75
However, as pointed out in comments, it might be wiser to use a library for date/time calculations.

Answer is wrong when calculating future value in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I am creating a future value application, that allows the user to enter the amount they have invested, the percent per year, how many years it is invested, and if it is compounded annually, semi-annually, monthly, daily, etc.
The problem I am having is that my answer is turning out wrong, but only by a couple hundreds.
With the code I have now, I am using the example for Semi-Annually:
PV = 1000
Interest Rate = 3
Years Invested = 10
Compounded = Semi Annually
The answer I get is 1806.
The correct answer is 1346.86, supposedly.
The code I have is here:
public void actionPerformed(ActionEvent event)
{
String input1 = textInitialAmount.getText();
String input2 = textAnnualInterest.getText();
String input3 = textNumberOfYears.getText();
String comp = textCompounded.getText();
double invest = Double.parseDouble(input1);
double interest = Double.parseDouble(input2);
double numberofyear = Double.parseDouble(input3);
if(comp.equals("Annually"))
{
double compPeriod = 1;
double compNumberOfYear = numberofyear * compPeriod;
double rate = (interest / 100) + 1;
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
if (comp.equals("Semi-Annually"))
{
double compPeriod = 2;
double compNumberOfYear = compPeriod * numberofyear;
double percentRate = interest / 100;
double rate = percentRate + 1;
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
if(comp.equals("Monthly"))
{
double compPeriod = 12;
double compNumberOfYear = compPeriod * numberofyear;
double rate = 1 + (interest / 100);
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
if(comp.equals("Bi-Weekly"))
{
}
}
}
Thanks for the help. Please comment if you need me to explain more.
Your problem is not related to coding... it's related to the way you're dealing with interest rates!
If you compound the interest Annually, you have 1 conversion period per year.
If you compound the interest Biannually (or "Semiannually" as your question says), you have 2 periods per year, and you have to convert the interest rate to an efective Biannual interest rate before computing the interest.
The correct code would be something like this:
double compPeriod = 2;
double compNumberOfYear = compPeriod * numberOfYear;
double percentRate = (interest / compPeriod) / 100;
// ^^^^^^^^^^^^^^^^^^^^^
// You missed this!
double rate = percentRate + 1;
double valueFuture = invest * Math.pow(rate, compNumberOfYear);
Do it by hand:
Interest rate: 3%
Compound periods: 2
Years: 10
Periods: 2 * 10 = 20
Efective interest rate: 3% / 2 = 1.5%
Investment: 1000
Future value: 1000 * (1 + 0.015)^20 = 1346.85500655
A little gift: Cleaner and simpler code (Because I'm a nice guy ;) )
You're aufully duplicating your code! You can clean it up:
public void actionPerformed(ActionEvent event) {
String input1 = textInitialAmount.getText();
String input2 = textAnnualInterest.getText();
String input3 = textNumberOfYears.getText();
String comp = textCompounded.getText();
double invest = Double.parseDouble(input1);
double interest = Double.parseDouble(input2);
double numberofyear = Double.parseDouble(input3);
// You just need to declare variables once!
double compPeriod;
switch(comp.toLowerCase()) {
case "annually":
compPeriod = 1;
break;
case "semiannually":
compPeriod = 2;
break;
case "monthly":
compPeriod = 12;
break;
case "bi-weekly":
compPeriod = 26; // Assuming 52 weeks per year
break;
case "weekly":
compPeriod = 52; // Assuming 52 weeks per year
break;
default:
compPeriod = 1;
}
double compNumberOfYear = numberofyear * compPeriod;
double valueFuture = invest * Math.pow(1 + (interest / compPeriod) / 100, compNumberOfYear);
String output = String.format("%5.0f", valueFuture);
futureValue.setText("The future value is " + output);
}
}

modulus and int for note calculations

Java input;
import java.util.*;
public class NetPay3
{
public static void main()
{
// Define Scanner object
Scanner inLine = new Scanner (System.in);
// Define other variables
float pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds,
OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
// Ask for the time in seconds
System.out.print ("Enter Net Pay : ");
pay = inLine.nextFloat();
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OneHundredPounds = (int) pay / 100;
// Calculate what is left over and store back into seconds
pay = pay % 100;
// Calculate the minutes. There are 60 seconds
// in a minute.
FiftyPounds = (int) pay / 50;
// Whatever is left over must be the seconds
pay = pay % 50;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
TwentyPounds = (int) pay / 20;
// Calculate what is left over and store back into seconds
pay = pay % 20;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FivePounds = (int) pay / 5;
// Calculate what is left over and store back into seconds
pay = pay % 5;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OnePound = (int) pay / 1;
// Calculate what is left over and store back into seconds
pay = pay % 1;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FiftyPence = (int) pay / 2;
// Calculate what is left over and store back into seconds
pay = pay % 2;
// Display the hours, minutes and seconds
System.out.println ("Amount of £100 notes " + OneHundredPounds);
System.out.println ("Amount of £50 notes " + FiftyPounds);
System.out.println ("Amount of £20 notes " + TwentyPounds);
System.out.println ("Amount of £5 notes " + FivePounds);
System.out.println ("Amount of £1 coins " + OnePound);
System.out.println ("Amount of 50p coins " + FiftyPence);
}
}
Screen input and output;
Enter Net Pay : 176.50
Amount of £100 notes 1
Amount of £50 notes 1
Amount of £20 notes 1
Amount of £5 notes 1
Amount of £1 coins 1
Amount of 50p coins 0
Hi relatively new to programming,
having trouble with me modulus and int operators in terms of getting them to function with the correct output on screen, previous syntax's worked correctly bar the 50p, anyone care to shed any light? thanks :)
Try changing FiftyPence = (int) pay / 2; toFiftyPence = (int) (pay / 0.5f);
Here is your code corrected and improved.
Don't use floats here, use integer arithmetic.
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
// Define Scanner object
Scanner inLine = new Scanner(System.in);
// Define other variables
int pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds, OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
OneHundredPounds = (int) pay / 10000;
pay = pay % 10000;
FiftyPounds = (int) pay / 5000;
pay = pay % 5000;
TwentyPounds = (int) pay / 2000;
pay = pay % 2000;
FivePounds = (int) pay / 500;
pay = pay % 500;
OnePound = (int) pay / 100;
pay = pay % 100;
FiftyPence = (int) pay / 50;
pay = pay % 50;
System.out.println("Amount of £100 notes " + OneHundredPounds);
System.out.println("Amount of £50 notes " + FiftyPounds);
System.out.println("Amount of £20 notes " + TwentyPounds);
System.out.println("Amount of £5 notes " + FivePounds);
System.out.println("Amount of £1 coins " + OnePound);
System.out.println("Amount of 50p coins " + FiftyPence);
System.out.println("Leftover pence: " + pay);
}
}
But I would further simplify this to (for example) this program:
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
Scanner inLine = new Scanner(System.in);
float[] val = new float[]{100, 50, 20, 5, 1, 0.5f, 0.2f, 0.05f, 0.02f, 0.01f};
int pay;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
for (int i=0; i<val.length; i++){
int m = ((int)(val[i] * 100));
int cnt = pay / m;
String s1 = val[i] < 1 ? " coins: " : " notes: ";
String s2 = val[i] < 1 ? "" : "£";
String s3 = val[i] < 1 ? "p" : "";
String s4 = val[i] < 1 ? m + "" : (m/100) + "";
System.out.println("Amount of " + s2 + s4 + s3 + s1 + cnt);
pay = pay % m;
}
}
}

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