calling a function to do another task - java

im calling a function to help work out a second calculation but it complies but dosnt return correct answer
tired a few different things but breaks codes so more then likely completely wrong
9. This question involves writing two functions.
a. The interest on a loan is currently 2.4% (0.024). If you take a £9000
loan to day you will pay 9000 * 0.024 ( £216) for a year. Start by writing a
function called calculateInterest which takes the loanAmount
(which can be any number not just 9000) as a float and a second argument
interestRate (also float can be any faction) which is the interest rate
for the loan. It should return a float which is the Interest (£216 in the
example above).
b. When calculateInterest works write a function called HW2I. (I=capital i)
This takes 2 float arguments. The original loan amount (float) and years
(an int) which is the number of years the loan will operate over (say 35).
Each year the interest is calculated (via a call to the calculateInterest
function). Interest is then added to the loan amount. This value (loan+
interest) is the new loan amount. Write the function HW2I. Don’t forget to
test it yourself to make sure it works correctly. Here is the pseudo code.
To HW2I ( loan, intreastRate , years )
Repeat with year = 1 to years
adjustedLoan = loan + calculateInterest( loan , intreastRate )
loan = adjustedLoan
end repeat
return loan
public float calculateInterest(float loanAmount, float interestRate) {
float intrest;
intrest = loanAmount * interestRate;
return intrest;
}
public float HW2I(float loan, int years) {
for (int i = 0; i <= years; i = i++) {
loan = loan + calculateInterest(9000, 0.24);
}
return (loan);
}

I guess we go to the same university because I have the exact same question so here's the answer:
public float calculateInterest(float loanAmount, float interestRate) {
float interest = (loanAmount * interestRate);
{
return interest;
}
}
public float HW2I(float loanAmount, float interestRate, int years) {
for (int i = 0; i < years; i++) {
float newLoanAmount = loanAmount + calculateInterest(loanAmount, interestRate);
loanAmount = newLoanAmount;
}
return loanAmount;
}
Good luck!
For the explanation:
The first method only asks us to calculate the interest, which is done by multiplying the loanAmount and the interestRate together. After, we return the interest.
For the second function, the pseudo code shows us that we need 3 arguments, which are float loanAmount, float interestRate and int years. It also says "Repeat with year= 1 to years" meaning we need to use iteration, so we do the for(int i= 0; i< years; i++ part. If we look back at the question we need a newLoanAmount which is the first loanAmount + a call to the first method, which is calculateInterest(loanAmount, interestRate). Now the loanAmount becomes the newLoanAmount, kind of replacing the value of the loanAmount before. Because the value has changed, we need to return loanAmount.
I hope this helps further and apologises if it isn't a great explanation; I started learning Java 2 months ago.

Related

java putting interest rate on my mortgage calculator

I made a code to calculate the monthly mortgage payment. Here is part of my code->
public static void printAmortizationSchedule(double principal, double annualInterestRate,
int numYears) {
double interestPaid, principalPaid, newBalance;
double monthlyInterestRate, monthlyPayment;
int month;
int numMonths = numYears * 12;
monthlyInterestRate = annualInterestRate / 12;
monthlyPayment = monthlyPayment(principal, monthlyInterestRate, numYears);
System.out.format("Your monthly Payment is: %8.2f%n", monthlyPayment);
for (month = 1; month <= numMonths; month++) {
// Compute amount paid and new balance for each payment period
interestPaid = principal * (monthlyInterestRate / 100);
principalPaid = monthlyPayment - interestPaid;
newBalance = principal - principalPaid;
// Update the balance
principal = newBalance;
}
}
static double monthlyPayment(double loanAmount, double monthlyInterestRate, int numberOfYears) {
monthlyInterestRate /= 100;
return loanAmount * monthlyInterestRate /
( 1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12) );
}
now, I need to add code that
1.The principal amount must be a non-negative number.
The mortgage payment will be determined by one of these amounts:
• 1 year 3.5%
• 2 year 3.9%
• 3 year 4.4%
• 5 year 5.0%
• 10 year 6.0%
I think I need to use do while statement, or if else code. However, I'm struggling to find where to put. Please help me!
In both cases you're dealing with a condition:
if the principal amount is negative, then don't perform the calculation, otherwise, proceed with the calculation.
if the mortgage is for n years then use r rate.
Hence, you'd use the if-then-else construct.
For the principle amount, check it early; It doesn't make sense to perform computations only to throw it all away because they are invalid. You can throw an exception to indicate the invalid input, a negative principal.
For the rate you just need to make sure you select the right one (with if-then-else) before you use it.

Calculating Interest (Java), the program should print the projected account balance after an arbitrary numbers of years

Please help me. Basically the program should Ask the user to input a number representing the initial balance of a savings account. Assign this number to a double variable called balance.
Ask for a number representing the yearly rate of interest (in percent) on the account. Divide this number by 100.0 and assign it to a double variable called rate. I have to use a loop to update the balance as it changes year by year. I am stuck on that part. Here is the code I have so far :
public static void calcInterest(){
System.out.println("Please enter the account balance : ");
System.out.println("Please enter the annual interest rate : ");
System.out.println("Please enter the number of years : ");
Scanner input = new Scanner (System.in);
double balance = input.nextDouble();
double y = input.nextDouble();
double rate = (y/100);
int years = input.nextInt();
}
There's no good reason to use a loop in this case, but I guess it's for learning purposes.
You can make a loop that calculates the new balance a year at a time like this:
for(int i = years; i > 0; i--)
balance = balance * y;
Alternatively use Math.pow(this follows the formula startvalue * rate of change^time = result):
balance = balance * Math.pow(y, years);

java compound interest with contributions formula

I am currently trying to develop a compound interest calculator that includes monthly contributions. I have successfully been able to get the compound interest calculation working without the monthly contributions using the following line of code, but cannot figure out what the formula should be when adding monthly contributions.
double calculatedValue = (principalValue * Math.pow(1 + (interestRateValue/numberOfCompoundsValue), (termValue * numberOfCompoundsValue)));
When trying to get the calculated value with contributions I changed the way this is done. See the following code how I approached this.
//The starting principal
double principalValue = 5000;
//Interest rate (%)
double interestRateValue = 0.05;
//How many times a year to add interest
int numberOfCompoundsValue = 4;
//The number of years used for the calculation
double termValue = 30;
//The monthly contribution amount
double monthlyContributionsValue = 400;
//How often interest is added. E.g. Every 3 months if adding interest 4 times in a year
int interestAddedEveryXMonths = 12/numberOfCompoundsValue;
//The total number of months for the calculation
int totalNumberOfMonths = (int)(12 * termValue);
for(int i = 1; i <= totalNumberOfMonths; i++)
{
principalValue += monthlyContributionsValue;
if(i % interestAddedEveryXMonths == 0)
{
principalValue += (principalValue * interestRateValue);
}
}
I figured this should do what I am after. Every month increase the principal by the contribution amount and if that month equals a month where interest should be added then calculate the interest * the interest rate and add that to the principal.
When using the values above I expect the answer $355,242.18 but get $10511941.97, which looks better in my bank account but not in my calculation.
If anyone can offer me some help or point out where I have gone wrong that would be much appreciated.
Thanks in advance
Your problem is here:
principalValue += (principalValue * interestRateValue);
You're adding a full year's interest every quarter, when you should be adding just a quarter's interest. You need to scale that interest rate down to get the right rate.
Here's an example:
class CashFlow {
private final double initialDeposit;
private final double rate;
private final int years;
private final double monthlyContribution;
private final int interestFrequency;
CashFlow(double initialDeposit, double rate, int years,
double monthlyContribution, int interestFrequency) {
if ( years < 1 ) {
throw new IllegalArgumentException("years must be at least 1");
}
if ( rate <= 0 ) {
throw new IllegalArgumentException("rate must be positive");
}
if ( 12 % interestFrequency != 0 ) {
throw new IllegalArgumentException("frequency must divide 12");
}
this.initialDeposit = initialDeposit;
this.rate = rate;
this.years = years;
this.monthlyContribution = monthlyContribution;
this.interestFrequency = interestFrequency;
}
public double terminalValue() {
final int interestPeriod = 12 / interestFrequency;
final double pRate = Math.pow(1 + rate, 1.0 / interestPeriod) - 1;
double value = initialDeposit;
for ( int i = 0; i < years * 12; ++i ) {
value += monthlyContribution;
if ( i % interestFrequency == interestFrequency - 1 ) {
value *= 1 + pRate;
}
}
return value;
}
}
class CompoundCalc {
public static void main(String[] args) {
CashFlow cf = new CashFlow(5000, 0.05, 30, 400, 3);
System.out.println("Terminal value: " + cf.terminalValue());
}
}
with output:
run:
Terminal value: 350421.2302849443
BUILD SUCCESSFUL (total time: 0 seconds)
which is close to the $355k value you found.
There are a number of different conventions you could use to get the quarterly rate. Dividing the annual rate by 4 is a simple and practical one, but the pow(1 + rate, 1 / 4) - 1 method above is more theoretically sound, since it's mathematically equivalent to the corresponding annual rate.
After some brief testing I've come to the conclusion that either you have:
miscalculated the value you want ($355,242.18)
OR
incorrectly asked your question
The calculation you've described that you want ($5000 start + $400 monthly contributions for 30 years + interest every 3 months) is found by the code you've provided. The value that it gives ($10,511,941.97) is indeed correct from what I can see. The only other suggestions I can offer are to only use double if you need to (for example termValue can be an int) AND when ever you know the value is not going to change (for example interestRateValue) use final. It will help avoid any unforeseen error in larger programs. I hope this helps you figure out your interest calculator or answers any questions you have.
static void Main(string[] args)
{
double monthlyDeposit;
double rateOfInterest;
double numberOfCompounds;
double years;
double futureValue = 0;
double totalAmount = 0;
Console.WriteLine("Compound Interest Calculation based on monthly deposits");
Console.WriteLine("Monthly Deposit");
monthlyDeposit = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Rate Of Interest");
rateOfInterest = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Number of Compounds in a year");
numberOfCompounds = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Number of year");
years = Convert.ToDouble(Console.ReadLine());
futureValue = monthlyDeposit;
for (int i = 1; i <= years * 12; i++)
{
totalAmount = futureValue * (1 + (rateOfInterest / 100) / 12);
if (i == years * 12)
futureValue = totalAmount;
else
futureValue = totalAmount + monthlyDeposit;
}
Console.WriteLine("Future Value is=" + futureValue);
Console.ReadLine();
}
//Output
Compound Interest Calculation based on monthly Deposits
Monthly Deposit
1500
Rate Of Interest
7.5
Number of Compounds in a year
12
Number of year
1
Future Value is=18748.2726237313

Calculating Compound Interest without math.pow in java

I need to calculate the monthly compounding interest in a savings account that is getting a monthly deposit. The variables I have to work with:
monthly savings ( Eg. I deposit $125.75 each month)
months (Eg. I deposit the same for 15 months)
APR (the ANNUAL interest is 5.65%)
Now I need to calculate the total savings amount, which for the given numbers here, the final answer should be $1958.88.
In essence, I am working with A = P(1 + r/12)^(12*t), where P is the amount I deposit * months, r is the APR, and t is the months/12 to get the "how many years"
The catch here is that I can not use the math.pow() as a requirement on the assignment, so my best guess is that I am to calculate it with a for/while loop similar to the following:
public static void main(String[] args)
{
double monthlySavings = 125.75;
double APR = 5.65;
int months = 15;
int monthCount = 0;
double totalSavings = 0;
while (monthCount < months)
{
totalSavings += monthlySavings + (1+APR/12/100);
mothCount++;
}
System.out.printf("Your total savings will be $%.2f\n", totalSavings);
}
The above code is NOT the correct solution, but its the closest i've come. The problem is that I am applying the interest to the monthly savings each time before it accumulates to the total. eg. it adds 125.75*interest for 15 deposits. What it SHOULD do is start with 125.75*interest then add 125.75, and then take the interest of the amount you have total so far, then add 125.75 and take the interest of the total amount again, and so on for the amount of months.
This is probably a lot easier than I am making it out to be, but I have tried for hours with adding different placeholder variables, but I am lacking some crucial concept, please help!
A loop for the number of months
for (int monthNumber = 0; monthNumber < numberOfMonths; monthNumber++)
{
}
then for each each month, add the interest then add the monthly savings. In that order, the other way around you end up with interest on money you just deposited, which is wrong.
totalSavings *= (APR / 12 / 100); //Although I would have separate variable for this
totalSavings += monthlySavings;
you don't really need to keep a month count but I prefer for loops.
After re-reading my question, I had an epiphany.. As I originally thought, the answer was a lot easier than I was making it out to be.
public static void main(String[] args)
{
double monthlySavings = 125.75;
double APR = 5.65;
int months = 15;
int monthCount = 0;
double placeHolder = 0;
double totalSavings = 0;
while (monthCount < months)
{
placeHolder += monthlySavings;
totalSavings = placeHolder * (1+APR/12/100);
placeHolder = totalSavings;
monthCount++;
}
System.out.printf("Your total savings will be $%.2f", totalSavings);
}

Java pass array to method for calculation and return array

I came across this post " pass array to method Java " on how to pass an array to a method however when trying to adapt it to my intrest calculator Ive got going I get errors such as "the operator / is undefined for the argument types double[],double" and I am unable to get it resolved. I am also looking to return the whole array since I need to print the results later on and eventually sort them.
For example I define my arrays and how big they can be and then call on the user to input loan amount, interest, and frequency calculated. After I get the data and its all in array format I then pass the whole arrays off to calculate simple interest and want to return the results as an array, and then pass the same initial arrays to find compound interest by month, week, and day but I get the previously mentioned error when it tries to do the division involved in "A = P(1+ (r/n))^(n*t)" The gathering data works fine I just cannot seem to pass arrays correctly or loop through them once I do IF I'm passing them right
Any and all assistance is appreciated as always.
Relevent code
call data from user
do {
arrPrincipalAmt[i] = getPrincipalAmount();
arrInterestRate[i]= getInterestRate();
arrTerm[i] = getTerm();
i++;
if (i < 4)
{
/*
* if "i" comes to equal 4 it is the last number that will fit in the array of 5
* and will Skip asking the user if they want to input more
*/
System.out.println("Enter another set of Data? (Yes/No):");
boolean YN = askYesNo();
if (YN == true)
{
more = true;
}
else if (YN == false)
{
more=false;
}
}
else
{
more = false;
}
}while(more);
while (run)
{
//Start calculations call methods
final int dINy = 365; //days in year
final int mINy = 12; //months in year
final int wINy = 52; //weeks in year
double loanYears =(double) arrTerm[i]/mINy; //convert loan months into fraction of years, or whole years with decimals.
arrSimple= calculateSimpleInterest(arrPrincipalAmt, arrInterestRate,loanYears);
//Simple IntrestloanAmount * (annualInterestRate/100.0) * loanYears;
arrCompoundMonthly = calculateCompundInterest(arrPrincipalAmt, arrInterestRate,mINy,loanYears);
//rewrite month compound:loanAmount * Math.pow((1+((annualInterestRate/100)/mINy)),(loanYears*mINy)) - loanAmount;
simple interest that fails
public static double[] calculateSimpleInterest(double[] arrPrincipalAmt, double[] arrInterestRate, double Years)
{
for(int i=0; i<arrPrincipalAmt.length; i++)
{
double simpInterest= arrPrincipalAmt[i] * (arrInterestRate[i]/100.0) * Years; //Simple Interest Calculation
}
return simpInterest;
}
compound interest that fails
public static double[] calculateCompundInterest(double[] arrPrincipalAmt, double[]
arrInterestRate, double frequency, double time)
{
/*The Compound Interest calculation formation is as follows:A = P(1+ (r/n))^(n*t) - P
A = total interest amount only.
P = principal amount (loan amount or initial investment).
r = annual nominal interest rate (as a decimal not a percentage).
n = number of times the interest is compounded per year.
t = number of years (don't forget to convert number of months entered by user to years).
*/
for (int i=0; i < arrPrincipalAmt.length; i++)
{
double[] compound= arrPrincipalAmt[i] * Math.pow((1+(arrInterestRate[i]/100.0)/frequency),(frequency*time)) - arrPrincipalAmt[i]; //Compound Interest monthly, weekly and daily depending on the frequency passed
}
return compound;
}
If you are getting an error like the operator / is undefined for the argument types double[],double it means that you are trying to divide the entire array by a value rather than a single element.
Change a line like myarray / value to myarray[i] / value
i checked your code and the problem is that at line 227 you define compound as a double array while the result of the expression at that line is simply a double.
I think you want to do so:
double[] compound = new double[arrPrincipalAmt.length];
for (int i=0; i < arrPrincipalAmt.length; i++) {
compound[i] = arrPrincipalAmt[i] * Math.pow((1+(arrInterestRate[i]/100.0)/frequency),(frequency*time)) - arrPrincipalAmt[i];
}
return compound;

Categories