Can you help me to determine the error here ?
Please please can you fix it please
import java.util.*;
import java.lang.*;
class Loan_payment
{
public static void main(String args[])
{
double inst=0.4, loan_amt=0.56, pay=0.34;
double mon = (inst/1200);
double quarterly = (inst/400);
double Half = (inst/200);
double annual = (inst/100);
//Mothly
double ad = 1 + mon;
double amt,amt_mon,amt2;
amt_mon = -1*((Math.log( 1 - ((mon * loan_amt) / pay))));
amt2 =(Math.log(ad));
amt = (amt_mon / amt2);
System.out.println("Number of Payments based on monthly : "+amt);
//Quarterly
ad = 1 + quarterly;
double amt_quart;
amt_quart = (( -Math.log( 1 - ((quarterly * loan_amt) / pay))));
amt = (amt_quart / amt2);
System.out.println("Number of Payments based on quarterly : "+amt);
//HalfYearly
ad = 1 + Half;
double amt_half;
amt_half = (( -Math.log( 1 - ((Half * loan_amt) / pay))));
amt = (amt_half / amt2);
System.out.println("Number of Payments based on HalfYearly : "+amt);
//Annually
ad = 1 + annual;
double amt_ann;
amt_ann = (( -Math.log( 1 - ((annual * loan_amt) / pay))));
amt = (amt_ann / amt2);
System.out.println("Number of Payments based on Annually : "+amt);
}
}
Can you help me to determine the error here?
No errors whatsoever, giving output :-
Number of Payments based on monthly : 1.6477856928143282
Number of Payments based on quarterly : 4.94607431098997
Number of Payments based on HalfYearly : 9.900315277456814
Number of Payments based on Annually : 19.833405363765696
Related
I'm pretty new to java, and I'm trying to write a program that will give me the monthly payments, interest total and total amount paid on a bank loan, but I believe either my math is wrong or is incorrectly formatted, because when I run it I get numbers in the negatives, and payments that I know are wrong. Could you point out where I have made the mistake?
Example :
7500 (amount borrowed)
14.5 (loan rate)
3 (# of years)
The expected output would be
258.16 (monthly payment)
1793.66 (interest paid)
9293.66 (total paid).
Code :
import java.io.*;
import java.util.*;
public class Prog58i
{
public static void main(String args[])
{
Scanner numberReader = new Scanner(System.in);
System.out.print("The amount I wish to borrow is? ");
int p = numberReader.nextInt();
System.out.print("The loan rate I can get is? ");
double r = numberReader.nextDouble();
System.out.print("How mny years will it take me to pay off the loan? ");
int m = (numberReader.nextInt())*12;
double MP = (1 +(r/1200));
MP = Math.pow(MP, m);
double payment = p *(r/1200) * (MP/(MP-1));
payment = (int)(m * 100+0.5)/100.0;
double total = (int)((m * payment)*100)/100.0;
double intetotal = (int)((total - p)*100)/100.0;
System.out.println("My monthly payments will be " + payment);
System.out.println("Total Interest Paid is " + intetotal);
System.out.println("Total amount paid is " + total);
}
}
According to your formula, this statement seems to be wrong
double MP = (1 + (r / 1200));
MP = Math.pow(MP, m);
The power is only on (r / 1200) not on (1 + (r / 1200))
For this program, I am trying to set up a payroll for inputted employees. The program has the user enter the employee's name, tax ID, and wage, and automatically generates an ID number for each employee entered. After this information is inputted, the user is asked to give the number of hours worked for 2 weeks. To do this, the employee ID number is entered to give reference to the employee that worked a certain number of hours. Next, either week 1 or 2 is entered to determine which week they worked. Finally, the number of hours worked that week is entered. Once the information is finished, the user enters 0 to stop entering the data, and the payroll is printed in a chart. The main issue I am having is that you MUST enter the ID, week, and hours for EACH employee added to the list, regardless of whether or not they worked in the 2 week period. I want to try and figure out how to set the Hours Worked and Total pay numbers to 0 if I do not enter any information for a certain employee. For example, if I enter: 1, for employee 1; 1, for week 1; 20, for hours worked in week 1; press enter; 1, again for employee 1; 2, for week 2; and 30, for hours worked in week 2, this information will print in the table. Say I have another employee, employee 2. I do not want to enter all of this information for employee 2 if they did not work at all in week 1 or 2, so the table should print 0 for Hours Worked, and 0 for Total Pay if I decide not to enter the ID, week number, and hours worked. Instead, however, it gives me an outOfBoundsException: Index: 1 Size: 1 Error when I try to do this. I was wondering if anyone had a solution to this. The 3 classes of my code are posted below. An example of the executed program with the outOfBoundsException is given in the main class.
import java.util.Scanner;
import java.util.ArrayList;
/**
* A class that contains methods for prompting a user for ACME employee information including names, tax IDs, and wages.
*/
public class EmployeeRecord
{
// ArrayLists used in methods.
ArrayList<String> employees = new ArrayList<String>();
ArrayList<String> tIds = new ArrayList<String>();
ArrayList<Double> wages = new ArrayList<Double>();
ArrayList<String> employeesLast = new ArrayList<String>();
Scanner in = new Scanner(System.in);
// Private Instance variables used in methods.
private String employeeId = "%03d";
private String employeeName = " ";
private String employeeNameLast = " ";
private String taxId = " ";
private double wage = 0.0;
/**
* A method that prompts the user to enter ACME employee names, tax IDs, and wages. This method also generates an ID number for each employee.
*/
public void setEmployeeInfo()
{
System.out.println("Please enter the names of each ACME employee, each employee tax ID, and each employee wage rate. Press Q when you are done entering names.");
while(!employeeName.equalsIgnoreCase("Q"))
{
employeeName = in.next();
if(employeeName.equalsIgnoreCase("Q"))
{
break;
}
employeeNameLast = in.next();
taxId = in.next();
wage = in.nextDouble();
employees.add(employeeName);
employeesLast.add(employeeNameLast);
tIds.add(taxId);
wages.add(wage);
System.out.println("Employee ID | Employee Name | Tax ID | Wage");
for(int i = 1; i <= employees.size(); i++)
{
System.out.printf(String.format(employeeId, i) + " | " + employees.get(i - 1) + " " + employeesLast.get(i - 1) + " | " + tIds.get(i - 1) + " | " + "%1.2f",wages.get(i - 1));
System.out.println();
}
}
}
/**
* A method that gets the list of ACME employee first names added to the record.
* #return
* Returns the ArrayList containing the first names of each employee entered.
*/
public ArrayList<String> getEmployeeArrayList()
{
return employees;
}
/**
* A method that gets the list of ACME employee last names added to the record.
* #return
* Returns the ArrayList containing the last names of each employee entered.
*/
public ArrayList<String> getEmployeeLastArrayList()
{
return employeesLast;
}
/**
* A method that gets the list of ACME employee tax IDs added to the record.
* #return
* Returns the ArrayList containing the tax IDs of each tax ID entered.
*/
public ArrayList<String> getTaxIdsArrayList()
{
return tIds;
}
/**
* A method that gets the list of ACME employee wages added to the record.
* #return
* Returns the ArrayList containing the wages of each wage entered.
*/
public ArrayList<Double> getWageArrayList()
{
return wages;
}
}
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
* A class that contains methods for entering payroll information for each ACME employee. This class uses methods from the EmployeeRecord class in order to run and therefore, relies on the EmployeeRecord class to operate.
*/
public class Employee
{
// ArrayLists that will implement return methods from the EmployeeRecord class.
ArrayList<String> eMp;
ArrayList<String> eMpL;
ArrayList<Double> eW;
// ArrayLists used to store values in setEmployeePayroll() method.
ArrayList<Integer> eId = new ArrayList<Integer>();
ArrayList<Double> hours = new ArrayList<Double>();
ArrayList<Double> tPay = new ArrayList<Double>();
// Instance Variables used in setEmployeePayroll() method.
private String employeeId = "%03d";
private int weekNumber = 0;
private double hoursWorked = 0.0;
private double hoursWorked2 = 0.0;
private int terminate = 1000;
private int i = 0;
Scanner in = new Scanner(System.in);
/**
* A method that implements the EmployeeRecord class to prompt the user to enter information for the payroll of each ACME employee. The payroll for each employee is then displayed.
*/
public void setEmployeePayroll()
{
// Constructs a new EmployeeRecord to implement classes from EmployeeRecord class.
EmployeeRecord e = new EmployeeRecord();
e.setEmployeeInfo();
eMp = e.getEmployeeArrayList();
eMpL = e.getEmployeeLastArrayList();
eW = e.getWageArrayList();
// Local variables used in this method.
double totalPay = 0.0;
double totalHours = 0.0;
double overTime = 0.0;
double overTime2 = 0.0;
System.out.println("Please enter ACME employee ID, the week they worked (1 or 2), and the number of hours worked. This information should be entered in the order the names were entered. Enter 0 when you are done inputing information.");
while(terminate != 0)
{
terminate = in.nextInt();
if(terminate == 0)
{
break;
}
weekNumber = in.nextInt();
if(weekNumber == 1)
{
hoursWorked = in.nextDouble();
}
else if(weekNumber == 2)
{
hoursWorked2 = in.nextDouble();
}
// Checks to see if an employee receives a 150% bonus on their payroll.
if(hoursWorked > 0 && hoursWorked <= 40 && hoursWorked2 > 0 && hoursWorked2 <= 40)
{
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1));
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked2 > 40 && hoursWorked > 0 && hoursWorked <= 40)
{
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1)) + (overTime2 * 1.5);
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 <= 40 && hoursWorked2 > 0)
{
overTime = hoursWorked - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1)) + (overTime * 1.5);
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 > 40)
{
overTime = hoursWorked - 40;
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1)) + (1.5 * (overTime + overTime2));
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
i = terminate;
}
// Constructs a new date format for the date of the payroll.
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date d = new Date();
// Gets current date and time for payroll.
System.out.println("ACME Payroll run on " + format.format(d));
System.out.println();
System.out.println("Employee Number | Employee Name | Hours Worked | Total Pay");
for(int i = 1; i <= e.getEmployeeArrayList().size(); i++)
{
System.out.println(String.format(employeeId, i) + " | " + eMp.get(i - 1) + " " + eMpL.get(i - 1) + " | " + hours.get(i - 1) + " | " + tPay.get(i - 1));
}
}
}
/**
* The main class that runs the contents of the EmployeeRecord and Employee classes.
*
*
*/
public class runPayroll
{
public static void main(String[] args)
{
Employee eE = new Employee();
eE.setEmployeePayroll();
}
}
/**
* Please enter the names of each ACME employee, each employee tax ID, and each employee wage rate. Press Q when you are done entering names.
Jane Smith 1010101 10
Employee ID | Employee Name | Tax ID | Wage
001 | Jane Smith | 1010101 | 10.00
John Smith 1111111 10
Employee ID | Employee Name | Tax ID | Wage
001 | Jane Smith | 1010101 | 10.00
002 | John Smith | 1111111 | 10.00
q
Please enter ACME employee ID, the week they worked (1 or 2), and the number of hours worked. This information should be entered in the order the names were entered. Enter 0 when you are done inputing information.
1 1 20
1 2 30
0
ACME Payroll run on 2015/09/15 22:25:19
Employee Number | Employee Name | Hours Worked | Total Pay
Exception in thread "main" 001 | Jane Smith | 50.0 | 500.0
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Employee.setEmployeePayroll(Employee.java:128)
at runPayroll.main(runPayroll.java:11)
*/
The problem exists at the bottom of the Employee class.
for(int i = 1; i <= e.getEmployeeArrayList().size(); i++)
{
System.out.println(String.format(employeeId, i) + " | " + eMp.get(i - 1) + " " + eMpL.get(i - 1) + " | " + hours.get(i - 1) + " | " + tPay.get(i - 1));
}
ArrayList is a zero-indexed list.
In short, imagine that you were to lay out all elements of a list as most people would think a list is:
1 2 3 4 5 6 7 8 9
That is a one-indexed list. A zero-indexed list (the type used in computer programming) is laid out like this:
0 1 2 3 4 5 6 7 8
If you want to access the first element, you have to get the element at position 0. If you want to get the 5th element, you have to get the element at position 4. It's a little backwards, but that's the way it's been for years, and it makes sense after dealing with lists and arrays for a while. For reasons why zero-indexed arrays are used, see here.
As for the code, you are trying to access it like a one-indexed list:
for(int i = 1; i <= e.getEmployeeArrayList().size(); i++)
There's only one entry in your list, so it looks like this:
0
The for loop starts iterating. It starts at int i = 1. Minor problem: there is no 1 index in the array. Java doesn't know what to do with it, so it blows up. To deal with a zero-indexed list, you should use
for(int i = 0; i < e.getEmployeeArrayList().size(); i++)
I am trying to do some calculations using different values stored in an array. The problem is that my array's values increase but the calculations are coming out decreasing.
Main:
public static void main(String[] args) {
double pay, rate, deposit;
int years;
char yes = 'y';
char answer;
double[] interest = new double[15];
interest[0] = 3.75;
interest[1] = 4.00;
interest[2] = 4.25;
interest[3] = 4.50;
interest[4] = 4.75;
interest[5] = 5.00;
interest[6] = 5.25;
interest[7] = 5.50;
interest[8] = 5.75;
interest[9] = 6.00;
interest[10] = 6.25;
interest[11] = 6.50;
interest[12] = 6.75;
interest[13] = 7.00;
interest[14] = 7.25;
mortgageClass mortgagePayment = new mortgageClass();
Scanner keyboard = new Scanner(System.in);
System.out.print("Are you a first time buyer? ");
answer = keyboard.next().charAt(0);
if (answer == yes)
{
mortgagePayment.setRate(4.50);
}
else
{
mortgagePayment.setRate(interest[0]);
}
System.out.print("What is your mortage term? ");
years = keyboard.nextInt();
mortgagePayment.setTermYears(years);
System.out.print("What is your amount of mortgage? ");
pay = keyboard.nextDouble();
mortgagePayment.setAmount(pay);
System.out.print("What is your deposit amount? ");
deposit = keyboard.nextDouble();
mortgagePayment.setdepositAmt(deposit);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
for ( int i = 0; i < interest.length; i++ ){
mortgagePayment.setRate(interest[i]);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
}
}
MortgagePayment Class
public class mortgageClass {
private double rate;
private double loanAmount;
private double depositAmt;
private int termYears;
public void setRate(double r) {
rate = r;
}
public void setAmount(double loan) {
loanAmount = loan;
}
public void setTermYears(int years) {
termYears = years;
}
public void setdepositAmt(double amount) {
depositAmt = amount;
}
public double getMonthlyPayment() {
rate /= 100.0;
loanAmount = loanAmount - depositAmt;
double monthlyRate = rate / 12.0;
int termMonths = termYears * 12;
double monthlyPayment = (loanAmount * monthlyRate)
/ (1 - Math.pow(1 + monthlyRate, -termMonths));
return monthlyPayment;
}
}
The output is decreasing
Your mortgage payment is 1309.00
Your mortgage payment is 1220.49 //my output
Your mortgage payment is 1128.42
When it should be increasing
Your mortgage payment is 1309.00
Your mortgage payment is 1331.44 //Expected output
Your mortgage payment is 1354.10
Obviously the first value is assigned correctly, so why isn't the increment working?
EDIT: I have added a print statement to see if the correct values are being used and it seems like they are
for ( int i = 0; i < interest.length; i++ ){
mortgagePayment.setRate(interest[i]);
//System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println(interest[i]);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
Output:
3.75
Your mortgage payment is 1309.00
4.0
Your mortgage payment is 1220.49
4.25
Your mortgage payment is 1128.42
4.5
Your mortgage payment is 1032.74
..... I would just like to know WHY the calculations are decreasing.
skip
interest[i] = i + 1;
EDITED 2nd time :
the problem is
loanAmount = loanAmount - depositAmt;
every time you call mortgagePayment.getMonthlyPayment()
it decreasing the loanAmount , Thats why monthly amount is coming down
suggested change :
public double getloanAmount(){
return loanAmount - depositAmt;
}
public double getMonthlyPayment() {
rate /= 100.0;
double loanAmount = getloanAmount();
double monthlyRate = rate / 12.0;
int termMonths = termYears * 12;
double monthlyPayment = (loanAmount * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -termMonths));
return monthlyPayment;
}
that will fix the problem.
EDITED :
use this fromula Monthly Mortgage Payment
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
The variables are as follows:
M = monthly mortgage payment
P = the principal, or the initial amount you borrowed.
i = your monthly interest rate. Your lender likely lists interest rates as an annual figure,
so you’ll have to divide by 12, for each month of the year. So, if your rate is 5%,
then the monthly rate will look like this: 0.05/12 = 0.004167.
n = the number of payments, or the payment period in months. If you take out a 30-year fixed rate mortgage,
this means: n = 30 years x 12 months per year = 360 payments.
I have not used java before and I am confused as to why a simple present value calculator I wrote is not working. The present value formula returns a super small number for some reason? See if you can spot my error:
// Import all utilities
import java.text.DecimalFormat;
import java.util.*;
// Base class
public class Project2
{
// Main function
public static void main(String[] args)
{
// Define variables
double p = 0.0;
double f = 0.0;
double r = 0.0;
double n = 0.0;
String another = "Y";
// Create a currency format
DecimalFormat dollar = new DecimalFormat("#,###.00");
// Create a new instance of the scanner class
Scanner keyboard = new Scanner(System.in);
// Loop while another equals "Y"
while(another.equals("Y"))
{
// Get future value
System.out.println("Future value: ");
f = Double.parseDouble(keyboard.nextLine());
// Get annual interest rate
System.out.println("Annual interest rate: ");
r = Double.parseDouble(keyboard.nextLine());
// Get Number of years
System.out.println("Number of years: ");
n = Double.parseDouble(keyboard.nextLine());
// Run method to find present value and display result
p = presentValue(f, r, n);
System.out.println("Present value: $" + p );
// Ask if user wants to enter another
System.out.println("Enter another?(Y/N) ");
another = keyboard.nextLine().toUpperCase();
}
}
public static double presentValue(double f, double r, double n)
{
// Do math and return result
double p = f / Math.pow((1 + r), n);
return p;
}
}
Assuming you enter the R as % per annum i.e. for e.g. R = 4.3%, you would want to modify the function as :
double p = f / (Math.pow((1 + (r/100.0)), n));
return p;
If this is not what you would want, you might want to enter the value of R=4.3% p.a as
4.3/100 = 0.043 and not 4.3.
Instead of future value Please take an input for Principal.
Your PresentValue Calculation Function will be like this. Try this function, hope you will get your perfect result
public double presentValue(double principal, double yearlyRate, double termYears)
{
// Do math and return result
double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
return pValue;
}
Math.pow expects the first argument to be the base and the second the exponent. ( See The Math javadoc )
In your program the first argument is the power and the second is the base.
Change that to double p = f / Math.pow(n, (1 + r)); and I expect your program to run as expected
Your program works fine. I just tested it.
Future value:
100000
Annual interest rate:
0.4
Number of years:
20
Present value: $119.519642774552
Enter another?(Y/N)
Y
Future value:
100000
Annual interest rate:
40
Number of years:
20
Present value: $5.550381891760752E-28
Enter another?(Y/N)
You're entering the interest rate wrong probably.
If you want to enter an integer value, you can modify the formula:
double p = f / (Math.pow((1 + (r/100.0)), n));
This will result in:
Future value:
100000
Annual interest rate:
40
Number of years:
20
Present value: $119.519642774552
Enter another?(Y/N)
I need help to iterate the calculations and list for months in a loop.
I don't know how to list the loan balance with updated information. This code lists items in each place but each number is the same as the last. The first months calculations are displayed for the entire 360 months.
Write the program in Java (without a graphical user interface)
using a loan amount of $200,000 with an interest rate of 5.75%
and a 30 year term. Display the mortgage payment amount and then
list the loan balance and interest paid for each payment over
the term of the loan. If the list would scroll off the screen,
use loops to display a partial list, hesitate,
and then display more of the list.
/Declare all Variables for Week 3/
double anualInterest = .0575;
double interestCompoundedMonthly = 0;
double interestForPeriod = 0;
double principalAtEndOfPeriod = 200000.00;
double portionToPrincipal = 0;
double amountOfPaymentMonthly = 1167.15;
double newPrincipalAtEndOfPeriod = 0;
/Calculate Payments Week 3/
interestCompoundedMonthly = (anualInterest/12); //.0575/12=.0047916
interestForPeriod = interestCompoundedMonthly * principalAtEndOfPeriod; // 958.32 =.0049916*200,000
portionToPrincipal = amountOfPaymentMonthly - interestForPeriod; // 208.83 = 1167.15-958.32
newPrincipalAtEndOfPeriod = principalAtEndOfPeriod - portionToPrincipal; //199791.18 = 200000-208.83
System.out.println (i+ "\t\t" + dcm.format(monthlyPayment)+"\t\t" +dcm.format(interestForPeriod)+"\t\t\t"+dcm.format(portionToPrincipal)+ "\t\t\t" +dcm.format(newPrincipalAtEndOfPeriod));
Thanks in advance for any advice.
/****************
* Week 2 *
****************/
/*Monthly Payment Program
A program written in Java (without a graphical user interface)
that will calculate and display the monthly payment amount
to fully amortize a $200,000.00 loan
over a 30 year term at 5.75‰ interest.*/
/****************
* Week 3 *
****************/
/* Write the program in Java (without a graphical user interface)
using a loan amount of $200,000 with an interest rate of 5.75%
and a 30 year term. Display the mortgage payment amount and then
list the loan balance and interest paid for each payment over
the term of the loan. If the list would scroll off the screen,
use loops to display a partial list, hesitate,
and then display more of the list.*/
import java.io.IOException; //Code that delays ending the program
public class Monthly_Payment_Calculator {
public static void main (String [] args) {
/*Declare all Variables Week 2*/
/*Variables provided by customer*/
double loanAmount = 200000.00; // $ amount borrowed
double interestRate = 5.75; // interest rate 5.75%
int years = 30; // years of loan
/*Variables needed for calculating*/
int months = 0; // months for calculating
double monthlyPayment = 0; // monthly payment for calculating
double interest = 0; // interest rate for calculating
/*Declare all Variables for Week 3*/
double anualInterest = .0575;
double interestCompoundedMonthly = 0;
double interestForPeriod = 0;
double principalAtEndOfPeriod = 200000.00;
double portionToPrincipal = 0;
double amountOfPaymentMonthly = 1167.15;
double newPrincipalAtEndOfPeriod = 0;
/*Variables for storing previous balances*/
java.text.DecimalFormat dcm = new java.text.DecimalFormat("$,###.00");
// format for currency
/*Calculate Payment Week 2*/
interest = interestRate / 100;
months = years * 12;
monthlyPayment = (loanAmount * (interest/12))/(1 - 1 /Math.pow((1 + interest/12), months));
/*Display the mortgage payment amount as per WK3 assignment*/
System.out.println ("Total Monthly Payment is ");
System.out.println (dcm.format(monthlyPayment));
/*Display columns*/
System.out.println("Month #\t Amount of Payment\tInterest for Period\tPortion to Principal\tPrincipal at End of Period\n");
System.out.println("0\t\t\t0\t\t0\t\t\t0\t\t\t"+ dcm.format(principalAtEndOfPeriod));
//Prints headers for columns
/*Loop to calculate and print monthly payments*/
for(int i=1; i <= months; i++) // 360 months
{
/*Calculate Payments Week 3*/
interestCompoundedMonthly = (anualInterest/12); //.0575/12=.0047916
interestForPeriod = interestCompoundedMonthly * principalAtEndOfPeriod; // 958.32 =.0049916*200,000
portionToPrincipal = amountOfPaymentMonthly - interestForPeriod; // 208.83 = 1167.15-958.32
newPrincipalAtEndOfPeriod = principalAtEndOfPeriod - portionToPrincipal; //199791.18 = 200000-208.83
System.out.println (i+ "\t\t" + dcm.format(monthlyPayment)+"\t\t" +dcm.format(interestForPeriod)+"\t\t\t"+dcm.format(portionToPrincipal)+ "\t\t\t" +dcm.format(newPrincipalAtEndOfPeriod));
//recalculate interest for period
//recalculate the portion to principal
//recalculate principal at end of period
//set the remaining balance as the mortgage loan for the next repetition
if(i%12==0 && i<months){
/*Code to delay ending the program*/
System.out.println( );
System.out.println( );
System.out.println ("(Please Press Enter to Continue the List)");
System.out.println( );
System.out.println( );
System.out.println("Month #\t Amount of Payment\tInterest for Period\tPortion to Principal\tPrincipal at End of Period\n");
try {
System.in.read(); //Read input from the keyboard
}
catch (IOException e) { //Catch the input exception
return; //and just return
}
}
}
}
}
You need to reset your principal balance at the end of the payment calculation. Try adding:
prindipalAtEndOfPeriod = newPrincipalAtEndOfPeriod;
I know it's been a while but maybe someone else will find this helpful.
i'm not sure how your interest works but i'm guessing that you are trying to compute a summation.
perhaps you can try the following in your 'for' loop:
// a is the cummulative sum
// b is the monthly calculation
a = a + b;