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.
Related
In Part 1 of a prompt, I am expected to integrate an equation into Java to get the value for a period (T). The equation is as follows: T = FS / (440 * (2 ^(h/12))
NOTE:
FS = sample rate, which is 44100 / 1.
h = halfstep, which is provided by the user.
An example of this equation is: 44100 / (440 * (2 ^(2/12)) = 89.3
The code I wrote is as follows:
public static double getPeriod(int halfstep) {
double T = 100; // TODO: Update this based on note
double FS = 44100 / 1;
double power = Math.pow(2, (halfstep / 12));
double denominator = 440 * (power);
double result = (FS) / (denominator);
T = Math.round(result);
return T;
}
// Equation test.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("halfstep is: ");
int halfstep = in.nextInt();
double period = getPeriod(halfstep);
System.out.print("Period: " + period + " ");
}
But when I run through this code with h = 2, T = 100.0 instead of the anticipated 89.3 and I am not sure what the issue is. Any thoughts on what's going on?
Because halfStep is an int, when you write
(halfstep / 12)
the calculation is done by taking halfStep / 12 and rounding down to the nearest integer. As a result, if you plug in 2 here, then halfStep / 12 will come back as 0 instead of 1/6. That's messing up the computation and is likely what's giving you the wrong answer.
You have a few options for how to proceed here. One would be to change halfStep to be a double rather than an int. Another would be to rewrite the division as
halfStep / 12.0
which, since 12.0 is a double literal, will perform the division in the way you intend.
One other potential issue - you declare the variable T as 100.0, but never use T anywhere in the calculation and ultimately overwrite it before returning it. I'm not sure whether this is intentional or whether that indicates that one of the formulas is incorrect.
Hope this helps!
I need to get a centimeter number input by the user, and then representing it as a combination of kilometers, meters, and centimeters. For example, 1005020 centimeters will be 10km, 50meters, and 20 centimeters.
I just started out and I feel It's a really basic question and I feel so frustrated.
I've tried to code and unfortunately can't reach the desired result
Scanner scanner = new Scanner(System.in);
System.out.println("This program takes centimeter number and represent it as a combination of kilometer, meter, and centimeter");
System.out.println("Please enter centimeters:");
double centimeters = scanner.nextDouble();
double convertedCentimeters = centimeters;
double kilometers = (int) (convertedCentimeters / 100000);
convertedCentimeters /= 100000;
double meters = (int)(convertedCentimeters / 100);
convertedCentimeters /= 100;
It will print 10km and 0.0 meters and 0.10050200000000001 centimeters.
I've tried without casting and km is wrong, tried to put everything as int and still wrong. I will really appreciate the help, I need to win this one. If you can lead me to the solution and not tell me it directly that will be great.
The major thing missing from your answer is use of the modulus, which you need to correctly answer your question. Consider the following working script:
int centimeters = 1005020;
int kilometers = centimeters / 100000;
int meters = (centimeters % 10000) / 100;
int centimetersFinal = centimeters % 100;
Given that you want to report whole numbers for each unit, I recommend starting off and working with integers everywhere. This also makes the arithmetic much easier.
The kilometer value is obtained by just taking the floor of the centimeter amount converted to kilometers. In this case, we get 10km, what you expect, but we don't include the remainder, because that goes to the meter and centimeter components.
The meter value takes the mod 10000 to isolate only the components that are strictly less than one kilometer. Then, we divide by 100 to remove the centimeter component.
Finally, the centimeter component is just the remainder when dividing the original amount by 100.
I'm working on a lesson to create a vacation plan. When I write code like
double money1 = money / days;
money1 = money*100;
money1 = (int) money1/ 100.0;
IntelliJ underlines money / days and notifies me that it's redundant.
Why does it happen? How can I make it not redundant?
You're immediately reassigning the variable, so your calculation is lost.
Observe:
double money1 = money / days;
money1 = money*100; // <- Quotient is discarded and overwritten
money1 = (int) money1/ 100.0; <- Prior product is discarded and overwritten
This is what IntelliJ is warning you about; this smells very much like a bug. I can't reliably tell you which of these statements to change since they do very different things, but this is something you should look to debug in your logical flow.
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.
So this project is a little outside of my comfort zone. I would describe my current stage of development as being one in which, “I know about things like: collection, design patters, and in general what makes for good OOP. But these things are sort of at my current limits. And so I probably don’t use them or attempt to use them as much as I should.”
I’m trying to change that, so I've been working on fairly small challenge/application that really lends itself to the above and asking myself to write smart, clean code. I’m fairly happy with what I've been able to do so far. However, I have two classes remaining that I still need to dive into. I have a lot of ideas about how to go about this. I’m sure some are good and some are bad, but more than anything, I think I’m over thinking things.
In short, here is what I’m trying to do, here is what I have, and here is where I need to go:
What I’m trying to do: The simplest way to state the goals for this app are, I have credit card (this class is the class I have done), I have wallets, and I have people. Looking at it from a high-level perspective, I’m putting cards in the wallets and wallets in the people. I have 3 cards, they really only differ in their ‘names’ and interest rates. I want some wallets to have 1 card and for others to have all three. As for wallets clearly every person needs at least one, but I’d like to give someone two. And that is really about it, I worked out some math for simple interest on the card which I’ll tie in at some point, but mostly I’m looking to build a clean and well-designed app.
What I have: As I've stated I more or less have the CreditCard class done. I’m still fine tuning it, but I've been able to improve it a lot and I’m casually happy with it. I’ll include this class below to provide context for the app and also, so you can provide suggestions if needed. At the top of the class you’ll see a lot of documentation. This is mostly just the math, and it’s logic, for working out simple interest. You’ll see. But I also have two test cases that I’m coding to, you’ll see this too.
Where I need to go: Well I have credit cards. Now I just need wallets and people. From my perspective, I could see the wallet making use of an ArrayList. Though, it could be the case that a different aspect of collections might serve better. I have mostly(mostly) used ArrayList, and so I keep mostly using ArrayList. It’s worked out so far… Beyond that, I have been considering making Wallet and Person abstract, which seems like a good idea, but once again, not much experience in making these choices.
So at the end of all of this, I’m look for some direction, conformation of good ideas and alternatives to weaker ones. If these could be combine with examples or if suggestions could express themselves in both words and code, this would be optimal because I get a lot more out of advice when I can see it in action. For me an OK suggestion with code, is ‘generally’ more helpful than a great suggestion without. It’s all about being able to apply that advice. But, that’s just me and everyone is different. What I can tell you, that is definite, is that all suggestion, whatever they are, will be appreciated and helpful. Because, I’m doing this, I’m here, to learn.
/*
* Test Cases:
* 1) 1 person has 1 wallet and 3 cards (1 Visa, 1 MC 1 Discover) – Each Card has a balance of $100 – calculate the total interest (simple interest) for this person and per card.
*
* 2) 1 person has 2 wallets Wallet 1 has a Visa and Discover , wallet 2 a MC - each card has $100
* balance - calculate the total interest(simple interest) for this person and interest per wallet
*/
/*
* Formula Key:
*
* Algebraic Symbols:
* A = Total Accrued Amount (principal + interest)
* P = Principal Amount
* I = Interest Amount
* r & R = Rate of Interest per year in percentage & decimal
* t = Time Period involved in months or years(duration pertaining to this equation)
*
* Rate of Interest, Percentage To Decimal Equations:
* R = r * 100
* r = R / 100
*
* Simple Interest Equation:
* A = P(1 + (r * t))
*/
/*
* Card:
* VISA 10%
*
* Equation:
* Accrued Amount(A) = Principle Amount(P) * (1 +(Interest Rate(r) * Time Period(t)))
*
* Calculation:
* First, converting Interest Rate(R) of 10%, to, Interest Rate(r) of 0.1
* r = R/100 = 10%/100 = 0.1 per year,
* put Time Period(t) of 1 month into years,
* months/year(1 month ÷ 12) = 0.08 years
*
* Solving Equation:
* A = 100(1 + (0.1 × 0.08)) = 100.8
* A = $ 100.80
*
* Solution:
* The total Amount Accrued(A), Principal(P) plus Interest(I),
* from Simple Interest on a Principal(P) of $ 100.00
* at a Rate(r = R/100(convert a percentage to a decimal)) of 10% or 0.1 per year
* for 0.08 years, 1 month(t) is $ 100.80.
*/
/*
* Card:
* MC(Master Card) 5%
*
* Equation:
* Accrued Amount(A) = Principle Amount(P) * (1 +(Interest Rate(r) * Time Period(t)))
*
* Calculation:
* First, converting Interest Rate(R) of 5%, to, Interest Rate(r) of 0.05
* r = R/100 = 5%/100 = 0.05 per year,
* put Time Period(t) of 1 month into years,
* months/year(1 month ÷ 12) = 0.08 years
*
* Solving Equation:
* A = 100(1 + (0.05 × 0.08)) = 100.4
* A = $ 100.40
*
* Solution:
* The total Amount Accrued(A), Principal(P) plus Interest(I),
* from Simple Interest on a Principal(P) of $ 100.00
* at a Rate(r = R/100(convert a percentage to a decimal)) of 5% or 0.05 per year
* for 0.08 years, 1 month(t) is $ 100.40.
*/
/*
* Card:
* Discover 1%
*
* Equation:
* Accrued Amount(A) = Principle Amount(P) * (1 +(Interest Rate(r) * Time Period(t)))
*
* Calculation:
* First, converting Interest Rate(R) of 1%, to, Interest Rate(r) of 0.01
* r = R/100 = 1%/100 = 0.01 per year,
* put Time Period(t) into years,
* months/year(1 month ÷ 12) = 0.08 years
*
*
* Solving Equation:
* A = 100(1 + (0.01 × 0.08)) = 100.08
* A = $ 100.08
*
* Solution:
* The total Amount Accrued(A), Principal(P) Plus Interest(I),
* from Simple Interest on a Principal(P) of $ 100.00
* at a Rate(r = R/100(convert a percentage to a decimal)) of 1% or 0.01 per year
* for 0.08 years, 1 month(t) is $ 100.08.
*/
public class CreditCard
{
private BrandOfCard brandOfCard;
private static final double PRINCIPAL_AMOUNT = 100.00;
private static final double TIME_PERIOD = 0.08;
public CreditCard(BrandOfCard brandOfCard)
{
this.brandOfCard = brandOfCard;
}
/*
* A = P(1 + (r * t))
*/
public double getAccruedAmount()
{
double accruedAmount;
accruedAmount = PRINCIPAL_AMOUNT * (1 + (brandOfCard.getInterestRate() * TIME_PERIOD));
return accruedAmount;
}
public enum BrandOfCard
{
VISA(0.1), MASTER_CARD(0.05), DISCOVER(0.01);
private final double interestRate;
BrandOfCard(double interestRate)
{
this.interestRate = interestRate;
}
public double getInterestRate()
{
return interestRate;
}
}
//bottom of class
public static void main(String[] args)
{
CreditCard visa = new CreditCard(BrandOfCard.VISA);
CreditCard masterCard = new CreditCard(BrandOfCard.MASTER_CARD);
CreditCard discover = new CreditCard(BrandOfCard.DISCOVER);
double accruedAmount;
accruedAmount = visa.getAccruedAmount();
System.out.println("Visa card, with a principle amount of $100.00, & an interest rate of 10%, " +
"has accrued $" + (accruedAmount - PRINCIPAL_AMOUNT) + " in interest, " +
"over the last monthly term.");
System.out.println("The total amount due on this card is now $" + accruedAmount);
accruedAmount = masterCard.getAccruedAmount();
System.out.println("Master Card card, with a principle amount of $100.00, & an interest rate of 5%, " +
"has accrued $" + (accruedAmount - PRINCIPAL_AMOUNT) + " in interest, " +
"over the last monthly term.");
System.out.println("The total amount due on this card is now $" + accruedAmount);
accruedAmount = discover.getAccruedAmount();
System.out.println("Discover card, with a principle amount of $100.00, & an interest rate of 1%, " +
"has accrued $" + (accruedAmount - PRINCIPAL_AMOUNT) + " in interest, " +
"over the last monthly term.");
System.out.println("The total amount due on this card is now $" + accruedAmount);
}
}
First of all don't go object happy! More objects != better code!
Look at this from a data perspective because that is where most OOP programmers lose their way. This stuff is stored relationally for a reason.
People make that an object
Wallet - This is simply a middle key to join n number of cards to a person.
CC make that an object since each CC has defined terms of payment, fees, interest rates, etc.
What you end up with is:
Table of users.
Table of cards.
The wallet, unless you want to assign particular attributes to it is really a non existent thing, since having the card owner Key in the CC record links cards to owners.
The rub is really applying payments. Just like the bank adds your deposits to your account before they start processing your checks or auto payments, you have to apply any posted payments before you calc the interest + fees value to add to the balance so:
for owners{
for cards with card.ownerID = owners.ID{
card.balance=card.balance-payments ;
card.balance=card.balance+calcInterest(card.balance, card.rate)+GetSumOfFees(card);
}
}
That is the basic batch job that every CC Issuer runs every night.
On the charging side of things it is the smallest code they can get away with sine this has to happen practically instantaneously at a pay terminal, etc. etc.
public static String chargeThis(String CCData, Double AMT){
CCNum = GetCCNum(CCData) ;
boolean isValid = validateCC(ccData);
if(isValid) return chargeCC(ccNum,AMT) else return rejectedTrans ;
}
About lists hash maps, etc in Java or vectors in C++...
ANY operation on those that sizes them will be blazingly fast right up until the point they exceed the size of the L2 cache! After they exceed the size of L2 cache they get stored in system RAM and their performance goes into the tank. At this point a linked list is superior, since adding or subtracting an element is simply inserting a node, or deleting a node.
Remember, getting advanced performance requires understanding the machine AND understanding how the JVM or compiler arranges things. In order from best to worst storage is as follows:
L0 cache - 1 cpu cycle
L1 cache - 2 cpu cycles
L2 cache - 5 to 10 cpu cycles
System Memory 1000's of cpu cycles
Ethernet ( getting data across the wire ) 10's of K cycles
Disk - 50 to 100 K cycles