Need help Java amortization table calculations - java

This is my homework it is due Monday the 16th.
I finally got the months to display right but the amounts are wrong.
Also, not necessary but it would be nice to stop and Print something between each loan.
Like loan 1, loan 2, loan 3...
Any help will be appreciated
/*Write the program in Java (without a graphical user interface)
and have it calculate the payment amount for 3 mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5%
- 30 year at 5.75%
Use an array for the different loans.
Display the mortgage payment amount for each loan
and then list the loan balance and interest paid for
each payment over the term of the loan.
Use loops to prevent lists from scrolling off the screen.*/
I have the months correct but the loan amounts are wrong.
import java.io.IOException; //Code that delays ending the program
class MonthlyRhondav4
{
public static void main ( String[] args) throws IOException{
double loanAmount = 200000.00; // $ amount borrowed
double monthlyPayment = 0; // monthly payment for calculating
double loanBalance;
double interestPaid;
double principalPaid;
int paymentCounter;
int lineCounter = 0;
java.text.DecimalFormat dcm = new java.text.DecimalFormat("$,###.00");
int termArray[] = {84, 180, 360}; // Different loan terms in months
double interestArray[] = {0.0535, 0.055, 0.0575};// Different interest rates for the loan
int k =0;// gonna be paymentIndex
/*Code to start the payment list*/
System.out.print("\n\nPlease Press Enter to Continue to the 3 Different Amortization Lists");
System.out.println ();
System.out.println ();
System.in.read();
System.in.read();
/*Display columns*/
System.out.println("Month \t Loan Amount Left\tInterest\t\tPrincipal \n"); //Prints headers for columns
System.out.println ();
/*Loop to calculate and print monthly payments*/
//for(k=0; k<3; k++){// k is going to be paymentIndex to loop through index
for (k = 0; k < interestArray.length; k++) {
for(paymentCounter =1; paymentCounter <= termArray[k]; paymentCounter++) // months through array
{
/********TROUBLE HERE***************************************************************************************/
monthlyPayment = ((loanAmount * (interestArray[k]) * termArray[k]) + loanAmount) / (termArray[k] * 12);
interestPaid = loanAmount*(interestArray[k]/12); //interest paid through array
principalPaid = monthlyPayment-loanAmount*(interestArray[k]/12); //principal paid
/*need to fig monthly payment+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
System.out.println(paymentCounter + "\t" + dcm.format(loanAmount) + "\t\t" + dcm.format(interestPaid) + "\t\t\t" + dcm.format(principalPaid));
lineCounter++; //Increment the display counter
if (lineCounter > 11 && paymentCounter < termArray[k]*12) //Check to see if 12
{
System.out.println ("Please Press Enter to Continue the List" ); //Code to delay ending the program
System.in.read();
System.in.read();
lineCounter = 0;
}
}
loanAmount = (loanAmount - (monthlyPayment-loanAmount*(interestArray[k]/12))); //Calculate new loan amount
}
}//ends public static void main
}//ends public class

One observation -- you're not doing anything with the loan balance. The reason why nothing is changing is that having computed the interest and principal amounts of a given payment, you're not reducing the loan balance by the principal portion of the payment. You need to change your code to display the current loan balance and to compute the principal/interest split from the current loan balance and not the original loan amount.
Edited
Ok -- I see you were trying to update the balance, but you have it outside the loop for the loan. That needs to be inside the loop so that it is updated for each payment. Also, you have things like loanAmount * (interestArray[k] / 12) over and over again. Consider using variables, such as
double interestPaid = loanAmount * (interestArray[k] / 12)
This will make your code easier to read and more maintainable since if you find a mistake in the calculation, you only have to fix the mistake in one place rather than having to fix it everywhere you had the calculation.
I also don't see where you're calculating the monthly payment. That's a function of the original loan amount, number of payments, and interest rate. Remember, the monthly payment is fixed and the interest/principal split of each payment will change as the loan is paid down. You might find http://en.wikipedia.org/wiki/Mortgage_calculator useful to figure out the formula for the monthly payment.

first : never ever use double to calculate something... That's an advice you have to remember. If you don't want to trust me, please search Google for "java double computation" or something like that, and you'll see. Or read the excellent book "Effective Java"
BigDecimal class is there to have correct numbers in Java

A lot of mistakes. For instance you never set the monthlyPayment to anything but 0. You also do not use loanBalance. loanAmount should be a constant. You can also simplify redundant calculations. Example:
interestPaid = loanBalance*(interestArray[k]/12);
principalPaid = monthlyPayment-interestPaid;
instead of
interestPaid = loanBalance*(interestArray[k]/12);
principalPaid = monthlyPayment-loanBalance*(interestArray[k]/12);
I am also not sure you have the correct interest rate formulas, but am not going to check until you remove some of the more obvious errors.

Related

Looking to get the yearly returns on this total compound interest calculator

I'm really new to Java so please excuse if this isn't the 100% right way to even write this code.
So I've been messing around with this code for about 6 hours now, and I can not for the life of me figure out how to fix this issue:
I have a compound interest calculator that takes user input for the variables of term length, initial amount, and APR. I can get the answer I want if it was just the simple one time calculation, but I really want it to show me the amount increased each year of a term. For example:
If the interest is calculated for 10 years, I want it to show me the amount for each year leading up to it. Right now all I get is a static number of 1, or infinity.
How do I get this program to show me the total amount for the term (i.e. the length of the user input investment), broken down per year with the amount shown per year?
The code is:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestCalculator {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
double initial; // the intial amount your loan is set for
int term; // the number of years you want to calculate
float yearlyrate; // interest rate
int repeat;
// System message to alert users to program use
System.out.printf("Hi there! I can calculate compound interest for you at a fixed interest
rate and term.\n\nPlease enter numbers without commas or symbols to get an accurate result!");
// Prompt for initial investment amount
System.out.println("\nPlease enter your initial investment.");
// Store value of user input for initial investment
initial = scan.nextDouble();
// Prompt for interest percentage
System.out.println();
System.out.println("Please enter the annual interest percentage.");
System.out.println();
// Store value of user input for interest amount
yearlyrate = scan.nextFloat();
// Prompt for length of the term for investment
System.out.println();
System.out.println("Please enter the length of your investment in years.");
// Store Value of user input for term length
term = scan.nextInt();
//For loop to set up calulations, repeats, and totals
for(repeat = 0; repeat < term; repeat++) {
System.out.println();
System.out.println("Your investment amount after" + (repeat+1) + "years is:");
// calculation for determining compound interest at a yearly rate and over the term
double total = Math.pow(initial * (1 + (yearlyrate/100) / 12) , 12/term);
// Displays the total value to the user
System.out.println("$" + total);
// Seperation line to clean it up
System.out.println();
// Close the scanner
scan.close();
}
}
}
Any help would be greatly appreciated because I am really out of my depth with this one.
Just a small change in your calculation logic:
// calculation for determining compound interest at a yearly rate and over the term
double total = initial * Math.pow((1 + (yearlyrate/100)) , (repeat+1));

How do I loop until I get the right answer?

I'm trying to program something that repeats itself until it gets the amount right. My program is basically a loan program that helps you figure out how long it'll take for you to pay off a loan with interest. So far, I managed to get the first month to print out (although not exactly right...), but I need it to keep repeating until the loan amount has been paid off. I hope that makes sense.
import java.util.*;
import java.io.*;
public class Project4{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
Scanner user_input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("Project4.out");
double lamnt;
double mpay;
double intrestrate;
double mnthintrest;
double mintrestrate;
System.out.print("Enter the Loan Amount: ");
lamnt = keyboard.nextDouble();
System.out.println();;
System.out.print("Enter the intrest rate (Ex:5.75): ");
intrestrate = keyboard.nextDouble();
System.out.println();
System.out.print("Enter the monthly payment you want to make: ");
mpay = keyboard.nextDouble();
System.out.println();
mintrestrate = intrestrate/12;
mnthintrest = lamnt*mintrestrate;
System.out.println("The first month intrest rate is:" + pay);
}
}
I was suggested using a while loop but I'm not too sure how to make the while loop keep going until the loan amount is paid off. Also yes I know the outcome isn't right, I'm working on that part. I'm not too sure how to space out the titles properly.
I need the output to look like this: (using 1000 in loan payment, 7.2 in interest rate, 25 for monthly pay)
Amount loan after payment #1 is: 981.00 Principle is: 19.00 Interest is: 6.00
Amount loan after payment #2 is: 961.89 Principle is: 19.11 Interest is: 5.89
So, if you want to use a while loop until your loan is paid off, just do something like:
while (lamnt > 0) {
// Do stuff to pay off the loan here.
}
As long as you're updating the lamnt within the loop, that should work.
Hope that helped!
;)
Edit: Also, make sure you're only creating scanners that you actually use. And don't forget to close them at the end of the scope!
Assuming that interest rate would be entered in percentage, the mnthintrest calculation would need an additional multiplication by 1/100 i.e. 0.01
mnthintrest = lamnt*mintrestrate*(0.01);
You also need to edit the variable pay to mpay
System.out.println("The first month intrest rate is:" + pay);
I think your logic for money paid per month should be ( as others suggested) - reducing the loan amount until it reaches zero.
Now coming to implementation, you will be reducing the amount and since we wouldn't want the original data ( variable) to be affected, we could first store it an temporary variable.
For keeping track of #number of payment, we can keep the month count in another variable.
You could think of something like this:
double temp = lamnt;
int monthNumber = 1;
while(temp>0){
mnthintrest = temp*mintrestrate*0.01;
double principlePaidPerMonth= mpay- mnthintrest;
temp = temp - principlePaidPerMonth; // reducing the principle amount paid before printing
System.out.println("\nAmount left after payment "+monthNumber+" is:" + temp);
System.out.println("This month intrest is:" + mnthintrest);
System.out.println("Principle paid is:" + principlePaidPerMonth);
monthNumber++;
}
// text to be printed could be different
It is a good practice to keep variable names as meaningful as possible and to declare the variables as much closer to their first use.
So you could declare the variables for interest and interest rate just at the time of initializing above where the while loop part starts.
double mintrestrate = intrestrate/12;
double mnthintrest = lamnt*mintrestrate;
For formatting, you could use System.out.printf() instead of println - this could help format the number of digits shown after decimal
For getting precision - you could use absolute/ceiling functions available in Math class.

Why is the last line of my code not printing? Also, what's the simplest way for me to round numbers to 2 decimals? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 6 years ago.
When running my program, the last line displaying yearly gas expense is not showing... what have I done wrong? Also would like some help rounding figures to 2 decimal points...
I tried implementing a few strategies but none of them worked.
Any help is appreciated!
public class GasExpenses {
public static void main(String[] args) {
//Use scanner in order to retrieve user input.
Scanner keyboard= new Scanner(System.in);
//Declare variables.
int milesPerWeek;
double milesPerGallon,costOfGas;
System.out.println("GAS EXPENSES");
//Get user input.
System.out.println("How many miles do you drive a week?");
milesPerWeek = keyboard.nextInt();
//Get user input.
System.out.println("How many miles per gallon does your auto get?");
milesPerGallon=keyboard.nextDouble();
//Get user input.
System.out.println("What is the current cost of gas?");
costOfGas=keyboard.nextDouble();
//Calculate miles per year.
int milesPerYear=(milesPerWeek*52);
//Display calculated yearly mileage.
System.out.println("At " + milesPerWeek + "miles per week, you travel "+
milesPerYear + " miles per year.");
//Calculate and display calculated weekly & yearly gallons of gas used.
double gallonsPerWeek=(milesPerWeek/milesPerGallon);
System.out.println("Gallons per week:" + gallonsPerWeek);
double gallonsPerYear=(gallonsPerWeek*52);
System.out.println("Gallons per year:" + gallonsPerYear);
//Calculate and display calculated weekly & yearly gas expense.
System.out.println("With gas at $" +costOfGas + " per gallon, you will
spend: ");
double weeklyGasExpense=(costOfGas*milesPerWeek);
System.out.println("Gas expense per week: $" +weeklyGasExpense);
double yearlyGasExpense=(costOfGas*milesPerYear);
System.out.println("Gas expense per year: $" +yearlyGasExpense);
//Calculate and display calculated weekly & yearly gas expense based on
increased gas price.
double costIncrease= (costOfGas+1);
System.out.println("If gas goes up by one dollar per gallon to $" +
costIncrease +(" per gallon, you will spend:"));
double weeklyIncreasedGas=(costIncrease*milesPerWeek);
double yearlyIncreasedGas=(costIncrease*milesPerYear);
System.out.println("Gas expense per week : $" +weeklyIncreasedGas);
System.out.print("Gas expense per year : $" +yearlyIncreasedGas);
}}
Run system.out.flush() at the end of your code to make sure everything is printed.
For the rounding you could try this answer round up to 2 decimal places in java?
For first question, this line works for me given your code:
System.out.print("Gas expense per year : $" +yearlyIncreasedGas);
For second do this:
double number = 111.12345;
double result = Math.round(number * 100.0) / 100.0;

Boolean Statement in WHILE loop doesn't make sense?

My while statement just doesn't seem to make sense to me, even though it works.
I want it to calculate the interest only as long as the countYears is less than the timeLimit....so if I set timeLimit to 5, it should only calculate 5 years worth of interest but the way I read the current while statement, it doesn't seem to say that. Maybe I am just reading it wrong?
public class RandomPractice {
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
double intRate, begBalance, balance;
int countYears, timeLimit;
System.out.println("Please enter your current investment balance.");
begBalance = Keyboard.nextDouble();
System.out.println("Please enter your YEARLY interest rate (in decimals).");
intRate = Keyboard.nextDouble();
System.out.println("Please enter how long (in years) you would like to let interest accrue.");
timeLimit = Keyboard.nextInt();
balance = begBalance * (1 + intRate);
countYears = 0;
/* The way I read this while statement is as follows
* "While countYears is GREATER than the timeLimit...calculate the balance"
* This makes no logical sense to me but I get the correct output?
* I want this code to calculate the investment interest ONLY as long as
* countYears is LESS than timeLimit **/
while (countYears >= timeLimit)
{
balance = balance + (balance * intRate);
countYears++;
}
System.out.println(balance);
}
}
That code you have, as it stands, does not generate the correct data, my transcript for eight years at one percent per annum follows:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
101.0
In other words, only one year of interest is added rather than eight years.
So either your compiler is totally screwy, your code is not what you think it is, or whatever test data and/or method you're using to check the interest calculation is lacking somewhat.
First, as you foreshadowed, you need to change the condition to be countYears < timeLimit.
In addition, you also need to remove the initial interest calculation before the loop since this would mean you'd get a full year's interest as soon as you deposit the money. With those two changes:
balance = begBalance;
while (countYears < timeLimit) {
balance = balance + (balance * intRate);
countYears++;
}
and you then get the correct value of:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
108.28567056280801
Your loop isn't being executed at all if you switch it to <= it will be correct.
Right now your output is what is calculated outside of the loop.

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.

Categories

Resources