How do I add fines? - java

I am new to coding and was wondering how would I go about coding this fine? I am pretty sure I am going about it the wrong coding way if anyone could help that would be greatly appreciated.
Below is what is expected:
The fine will be a dollar value, which is a double data type. ParkingTicket will not have a double-typed fine variable. Instead, it calculates the fine on-demand, using the minutesPaid and minutesParked variables.
Impark levies a flat-rate fine of $20 (always), plus $10 aggravated penalties for every whole hour (60 minutes) parked beyond the paid amount. As a Canadian institution, Impark is also obligated to add the 5% Goods and Services Tax surcharge. A surcharge is multiplied after all other sums have been calculated.
You are responsible for producing the result of this calculation in calculateFine().
So far this is what I have, :
public static double calculateFine()
{
double meterMinutesPaidWithTax = 20*0.05;
double meterMinutesPaid = 20;
double pentalty = 10;
double tax = 0.05;
double overParked = (carMinutesParked+=1);
if(carMinutesParked<=carMinutesParked){
return meterMinutesPaidWithTax = meterMinutesPaidWithTax+meterMinutesPaid;
}
else if(carMinutesParked>overParked){
return meterMinutesPaid = (meterMinutesPaid + pentalty)*tax+(meterMinutesPaid + pentalty);
}
else{
return meterMinutesPaidWithTax;
}
}

Related

CURRENCY - Round double value ONLY if it has more than 2 decimal places [duplicate]

This question already has answers here:
Why not use Double or Float to represent currency?
(16 answers)
Closed 3 years ago.
I'm trying to split a bill and need to calculate how much each person would owe if the bill was split in even amounts. I know one amount will be different than the rest to account for the lost cents.
Assume 3 people try to split a bill for 200. 200 / 3 is 66.6666666667. What I planned on doing was charging the 2 first people 66.67 and the last gets lucky with the 66.66 bill.
At the minute, I have this so far:
private String calculateAmountToPay(String noOfParticipants, String owed) {
double amountOwed = Double.parseDouble(owed);
int noOfMembers = Integer.parseInt(noOfParticipants);
DecimalFormat amountFormat = new DecimalFormat("#.##");
amountFormat.setRoundingMode(RoundingMode.CEILING);
return amountFormat.format((amountOwed/(double)noOfMembers) / 100);
}
But this always will return 66.67. Is there a way that I can get it to only round up if there is a number greater than 2 decimal places, if not, it stays at 66.66 for example?
Maybe I'm approaching this the wrong way. I know currency can be finicky to deal with.
Before even thinking about arithmetic, you need to know that double is not an appropriate data type for use with currency, because it’s imprecise. So, stop using a floating point type (eg double) as the data type for the quantity of dollars and start using a precise type (eg long) as the data type for the quantity of cents.
The steps then to do the calculation would be to immediately convert everything, with rounding, to cents:
double amountOwed = ...;
int noOfMembers = ...;
long centsOwed = Math.round(amountOwed * 100);
long portionCents = Math.round(amountOwed * 100 / noOfMembers);
long errorCents = portionCents * noOfMembers - centsOwed;
Here’s one way to deal with the error:
long lastPortionCents = portionCents - errorCents;
But it’s possible that the error is more than 1 cent, so a better solution would be to spread the error out evenly by subtracting (or adding if the error is negative) 1 cent from the first (or last, or randomly chosen) errorCents diners.
The rest of the solution is then about rending the above, which I leave to the reader.
As a side note, using cents is how banks transmit amounts (at least for EFTPOS anyway).
Regarding basic software design, I would create a separate method that accepts integer cents and people count as its parameters and returns an array of the "split" amounts. Doing this will not only make your code easier to read, but it will compartmentaise the arithmetic operation and thus enable lots of simple tests to more easily be written, so you can know you have all the edge cases that you can think of covered.
You can use BigDecimal with half rounding mode:
private String calculateAmountToPay(String noOfParticipants, String owed) {
double amountOwed = Double.parseDouble(owed);
int noOfMembers = Integer.parseInt(noOfParticipants);
BigDecimal amount= new BigDecimal((amountOwed / (double) noOfMembers) / 100);
return amount.setScale(2, RoundingMode.HALF_UP).toString();
}
You can just do all the computation with basic primitives converting everything to cents (2 decimals precision), and dividing the left over cents over a portion of the members, no need to overcomplicate it with extra sdks/math manipulations. The following is a working example solving this problem entirely, using these suggestions:
public class AmountDivider {
private int totalMembers, luckies, unluckies;
private double totalAmount, amountPerLucky, amountPerUnlucky;
public AmountDivider(int numMembers, double amountOwed) {
totalMembers = numMembers;
totalAmount = amountOwed;
double centsOwed = amountOwed * 100;
int centsPerMember = (int)(centsOwed / totalMembers);
int centsLeft = (int)centsOwed - centsPerMember * totalMembers;
luckies = totalMembers - centsLeft;
amountPerLucky = centsPerMember / 100.0;
unluckies = centsLeft;
amountPerUnlucky = (centsPerMember + 1) / 100.0;
}
public String toString() {
String luckiesStr = String.format("%d lucky persons will pay %.2f", luckies, amountPerLucky);
String unluckiesStr = String.format("%d unlucky persons will pay %.2f", unluckies, amountPerUnlucky);
return String.format("For amount %f divided among %d: \n%s\n%s\n",
totalAmount, totalMembers, luckiesStr, unluckiesStr);
}
public static void main(String[] args) {
System.out.println(new AmountDivider(3, 200));
System.out.println(new AmountDivider(17, 365.99));
}
}
Complete code on GitHub
Hope this helps.

Java output with currency formating, percentages, and half_up rounding

JAVA OUTPUT Question, please help.
How to format two outputs, first is to have an ouput using HALF_UP rounding and currency formating and the second is to have an ouput with precentage?
Supporting docs:
(A) orginal assignment
Introduction to Object-Oriented Programming
Programming Assignment – Discount Coupon
A supermarket awards coupons depending on how much a customer spends on groceries. For example, if you spend $50, you will get a coupon worth eight percent of that amount. The following table shows the percent used to calculate the coupon awarded for different amounts spent. Write a program that calculates and prints the value of the coupon a person can receive based on groceries purchased and the amount paid after the discount is applied.
Money Spent
Coupon Percent
Less than $10
No coupon
Between $10 and $60
8%
Between $61 and $150
10%
Between $151 and $210
12%
More than $210
14%
Note, as specified, it is not clear how to handle boundary conditions. For example, what is the coupon percent for $150.25? You should decide how you are going to handle boundary conditions and be sure to explain your choice in the program documentation.
Your program should use a currency instance for formatting dollar amounts and a percent instance for formatting percents. They can both be found in the java.text.NumberFormat package. Use the HALF_UP rounding mode for your currency displays.
Here is a sample run:
run:
Please enter the cost of your grocies: 78.24
You earned a discount of $7.82. (10% of your purchase)
Please pay $70.42. Thank you for shopping with us!
(B) code so far
import java.util.Scanner;
import java.text.NumberFormat;
public class Coupon {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
NumberFormat currency = NumberFormat.getCurrencyInstance();
//Variables
double amountSpent=0;
double couponAmount = 0;
double totalAfterCoupon= 0;
final double lessThanTen = 0.00;
final double betweenTenAndSixity = 0.08;
final double betweenSixtyOneAndOneHundredAndFifty = 0.10;
final double betweenOneHundredAndFiftyOneAndTwoHundredAndTen = 0.12;
final double overTwoHundredAndTen = 0.14;
System.out.print("Please enter the cost of your groceries: ");
amountSpent = input.nextDouble();
if (amountSpent<10 && amountSpent>=0)
{
couponAmount = lessThanTen * amountSpent;
System.out.printf("You earned a discount of ", currency.format(couponAmount), "(0% of your purchase)");
}
else if (amountSpent>=10 && amountSpent<=60.49)
{
couponAmount = betweenTenAndSixity * amountSpent;
System.out.printf("You earned a discount of ", currency.format(couponAmount), "(10% of your purchase)");
}
else if (amountSpent>=60.50 && amountSpent<=150.49)
{
couponAmount = betweenSixtyOneAndOneHundredAndFifty * amountSpent;
}
else if (amountSpent>=150.50 && amountSpent<=210)
{
couponAmount = betweenOneHundredAndFiftyOneAndTwoHundredAndTen* amountSpent;
}
else if (amountSpent>210)
{
couponAmount = overTwoHundredAndTen* amountSpent;
}
else
{
System.out.println("Please enter your total bill between $0.00 or greater. ");
}
System.out.printf("the coupon amount is: %f ", couponAmount);
}
}
Note: I notice you're a newcomer and I'm gonna give you this one for free (We've all need to learn things first), but please keep in mind that ther are certain rules in SO; Asking for homework corrections or bad research related questions aren't appreciated, specially if they both apply. Also as tnw mentioned you should narrow your question down to the specific part of code that's relevant, so that it can easily be reproduced or/and found by others that have the same issue.
In case of the answer to your formatting problem you have some amazing resources at Oracle's official docs, learn how to use their docs and you'll get the hang of Java in no time. On the NumberFormat class they have this: https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html , and you will also need the info on locale's in Java: https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html .
What you need to do to use the NumberFormat class is create an instance of the locale you're going to use like: Locale enUSLocale = new Locale.Builder().setLanguage("en").setRegion("US").build();
There are multiple other ways to do this.
And then use this locale to indicate the NumberFormat class what to use:
//Instantiate the NumberFormat:
NumberFormat USFormat = NumberFormat.getCurrencyInstance(enUSLocale);
//And print it:
System.out.println("You earned a discount of " + USFormat.format(couponAmount));
Well I hope this gives you the basis you need to go on and learn to use the docs and other info online!
Goo(gle)d Luck!

Calculating future investment amount in Java

I'm trying to calculate the future investment amount in Java.
My program runs, but it's not giving me the correct answer.
If the
investmentAmount is 1000.56,
interest rate is 4.25, and
number of years is 1,
the answer should be $1043.92.
The formula we have to use is futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) ^ numberOfYears * 12
Below is my class
// Import Java Scanner
import java.util.Scanner;
public class Ex_2_21 {
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter investment amount, annual interest rate, and number of years
System.out.println("Enter investment amount:");
System.out.println("Enter annual interest rate:");
System.out.println("Enter number of years:");
float investmentamount = input.nextFloat();
float interestrate = input.nextFloat();
float numberofyears = input.nextFloat();
float years = numberofyears * 12;
//Formula to calculate the accumulated value
float futureInvestmentValue = (float) (investmentamount * Math.pow((years), 1 + interestrate));
//Print result
System.out.println("The accumulated value is " + futureInvestmentValue);
}
}
On top of what #Luiggi said, did you consider that if it is 4.25 interest rate, that is 425% interest rate, what you want is 1 + 0.0425
You're using years (equal to years * 12) when you mean months, and you're not using monthly interest rate at all. Divide annual interest rate (as entered) by 12 to get monthly interest rate (and also make sure it's a fraction, not a bare percentage, so if they're entering 4.25 it needs to be divided by 100 to get .0425), and introduce a new variable for total month duration. Then (as Luiggi notes) swap the argument order.
float futureInvestmentValue = (float) (investmentAmount * Math.pow(1 + monthlyInterestRate, months));
Here's the problem:
Math.pow((years), 1 + interestrate)
It should be
Math.pow(1 + interestrate, years)
As noted in Math#pow(double a, double b):
Parameters:
a - the base
b - the exponent
Returns
The value ab
There are two problems in the above given Java program:
Lack of problem understanding (kindly, take this suggestion in a positive interest. If we, understand the problem correctly, we are very much near to its correct programming solution.)
Formula for future investment value (A) is as follows:
a) Compounded annually:
A = P*(1+R)^N
Where, A = Future value, P = Original amount invested, R = Interest rate (given as %, in calculation use as R/100), N = Time period for which compound interest rate is applied (in years)
b) Compounded monthly:
A = P*(1+(R/12))^(N*12)
Where, A = Future value, P = Original amount invested, R = Monthly interest rate (given as %, in calculation use as R/100, it is not annual interest rate), N = Time period for which compound interest rate is applied (in years)
As per values of given sample problem, we find in order to calculate future investment value, we should be using formula (b).
So, w.r.t above given Java program, to incorporate this correction we need to simply add one more statement after the interestrate variable declaration line:
interestrate = interestrate / (100 * 12);
Second problem is lack of understanding of Java programming language constructs / logical error by ignorance. Whatever is the case; it does not matter. Technically, it is a programming error and thus it needs rectification.
As already suggested above by Luiggi Mendoza, in Java programming language if we want to express mathematical expression A^B then we have to use java.lang.Math.pow() method with following syntax:
public static double pow(double A, double B)
So, again w.r.t above given Java program, to incorporate this second correction we have to simply correct the line which declares the futureInvestmentValue variable and using the Math.pow() method; as follows:
float futureInvestmentValue = (float) (investmentamount * Math.pow(1 + interestrate, years));
Incorporating these two corrections, we make our solution correct. Based on the principle of GIGO (Garbage In Garbage Out, Gold In Gold Out) we will definitely get correct and exact answer to our any sample problem given values; as expected.
Happy Programming.

how to find out price/extra$1000 deposited

The formula that I want to convert in java is
Over limit Cash Deposit Fee = [(Input $ cash deposit) – ($ Cash deposits included in plan)] / 1000 * (price/each extra $1000 deposited)
The code that I am writing is
int inputCash = 50;
int cashDepsitFromPlan = 40;
int cashDepositOverLimitFee = 2.5;
cashDepositOverLimit = (double) ((inputCash -cashDepsitFromPlan) / 1000) * ???;
how do I find ???(price/each extra $1000 deposited)
If you're working with floating point numbers, you may want to reconsider the use of the int data type.
This, for a start, is going to cause all sorts of grief:
int cashDepositOverLimitFee = 2.5;
You're better off using double for everything.
In terms of finding the unknown variable here, that's something specific to your business rules, which aren't shown here.
I'd hazard a guess that the price/$1000 figure is intimately related to your cashDepositOverLimitFee variable such as it being $2.50 for every extra $1000.
That would make the equation:
inputCash - cashDepsitFromPlan
cashDepositOverLimit = ------------------------------ * cashDepositOverLimitFee
1000
which makes sense. The first term on the right hand side is the number of excess $1000 lots you've deposited over and above the plan. You would multiply that by a fee rate (like $2.50 or 2.5%) to get the actual fee.
However, as stated, we can't tell whether it's $2.50 or 2.5% based on what we've seen. You'll have to go back to the business to be certain.
You have to algebraically manipulate the equation to solve for that.
cashDepositOverLimitFee = (double) ((inputCash -cashDepsitFromPlan) / 1000) * ???
cashDepositOverLimitFee*1000 = (double) (inputCash -cashDepsitFromPlan) * ???
(cashDepositOverLimitFee*1000) / (double) (inputCash -cashDepsitFromPlan) = ???
??? = (cashDepositOverLimitFee*1000) / (double) (inputCash -cashDepsitFromPlan)
Note that the (double) cast must remain in order to ensure a floating point result.

Beginner Needing Java Programming Help! I can't figure out how to go about solving this

I am a beginner to Programming in Java and I cannot figure out how to solve this problem:
"Create an Investment application that calculates how many years it will take for a $2,500 investment to be worth at least $5,000 if compounded annually at 7.5%"
I have tried using a for loop and a do-while loop to try solving the problem but it doesn't work. Please Help!
This is what I have after trying everything so far:
/*Investment.java
*This program determines how many years it would take for $2500 to turn into $5000 if
*compounded at 7.5% annually.
*Date: October 27th, 2012
*/
/**
* The following application calculates how many years it will take for $2500 to
* turn into $5000 if compounded at 7.5% annually.
*/
public class Investment {
public static void main(String[] args) {
final int MAX_AMOUNT = 5000;
int investment = 2500;
double interest = 0.075;
double totalValue;
do {
totalValue = (investment + (investment * interest));
} while (totalValue < MAX_AMOUNT);
System.out.println(totalValue);
}
}
Help would be greatly appreciated!
Thanks,
The problem here is that you're just computing the value investment + investment*interest over and over again, and storing it in totalValue. Instead, you need to be accumulating. It could look like:
totalValue = investment;
do {
totalValue = (totalValue + totalValue*interest);
}
while (totalValue < MAX_VALUE);
This way, you keep actually adding the interest and accumulating it.
Additionally, as was commented, you're looking for the number of times that the loop looped, rather than just the value at the end. So you need to count the number of times that the loop is repeated by incrementing a counter each time.
You can do this in a single line, using basic math.
the time (n) to have a value (V) in the futue if initial amount (A) at interest rate (i) compuonded c times per year : n = [ln(V) - ln(A)] / [ ln(c+i) - ln(c)]
double getYearsToMature(double v, double i, int c, double a)
{
return (Math.log(v) - Math.log(a))/(Math.log(c+i) - Math.log(c));
}
since it says in the problem "at least $5000" just round it up and cast to int..
int answer = (Integer) Math.round(getYearsToMature(...));
also you will get some compiler warnings about loss of precision for casting from long to Integer - use float instead of double, or ignore warnings if your numbers are small
You may be able to solve this in a simpler manner by searching for appropriate formulas for calculating this (instead of using a loop). While programming, it's not only important to understand and use language constructs (like loops and conditions) properly, but also to learn the best "algorithm" to do it in an optimal way.
From http://www.csgnetwork.com/directcalccompinttrainer.html (one of the links found through a search):
The time period (n) to have FV in the future if the initial investment A at i interest compounded c times per year:
ln(FV) - ln(A)
n = ------------------
ln(c + i) - ln(c)
NOTE: ln is the natural logarithm function.
For annually compounded interest, the formula becomes:
ln(FV) - ln(A)
n = ------------------
ln(1 + i) - ln(1)
Here's the code using this formula (it'll give you the exact number of years, including a fraction, which you can adjust/truncate and print):
import java.lang.Math;
public class Investment {
public static void main(String[] args) {
final int MAX_AMOUNT = 5000;
int investment = 2500;
double interest = 0.075;
double years;
years = (log(MAX_AMOUNT) - log(investment)) / (log(1 + interest) - log(1))
System.out.println(years);
}
}
Something like:
double years = 0;
while(interest < totalvalue) {
totalValue = investment*interest;
years++;
}
?
To do it iteratively, note that you need to compute the number of years, not the investment amount. Your loop is not adding to the total value, it's recomputing it as if it were the first year each time through the loop. This would work instead:
public class Investment {
public static void main(String[] args) {
final int MAX_AMOUNT = 5000;
int investment = 2500;
double interest = 0.075;
double totalValue;
int years = 0;
do {
totalValue += totalValue * interest;
years++;
} while (totalValue < MAX_AMOUNT);
System.out.println(years);
}
}
However, a better approach is to look at the formula for total value after N years at I percent per annum return, compounded annually:
currentValue = initialInvestment * (1 + I)N
Then you can solve for N, plug in 2500 for initialInvestment and 7500 for currentValue. This will generally give you a fractional value for N, which you then need to round up to get to the number of years needed to reach or exceed the target amount. You'll find the Math.log() (or Math.log10()) function useful for this.

Categories

Resources