Need help Java amortization table - java

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;

Related

Monthly payment input calculator

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 loop increments array backwards

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.

Java Loan Amortization

Please what could be wrong with my code. it is an iteration approach to: The monthly payment for a given loan pays the principal and the interest. The monthly interest is computed by multiplying the monthly interest rate and the balance (the remaining principal).
The principal paid for the month is therefore the monthly payment minus the
monthly interest. Write a program that lets the user enter the loan amount, number of years, and interest rate and displays the amortization schedule for the loan.
However, i keep getting NaN just to calculate monthly payment.code is as follow:
import java.util.Scanner;
public class Amortization {
public static void main(String[] args) {
//create Scanner
Scanner s = new Scanner(System.in);
//prompt Users for input
System.out.print("Enter loan Amount:");
int loanAmount = s.nextInt();
System.out.print("Enter numberof Years:");
int numberYear =s.nextInt();
System.out.print("Enter Annual Interest Rate:");
int annualRate = s.nextInt();
double monthlyrate= annualRate/1200;
double monthlyPayment = loanAmount*monthlyrate/(1 -1/Math.pow(1+monthlyrate,numberYear*12));
System.out.printf("%6.3f",monthlyPayment);
// TODO code application logic here
}
}
I just wrote code for a similar problem. I share with you my solution.
I got a lot of ideas from http://java.worldbestlearningcenter.com/2013/04/amortization-program.html
public class LoanAmortizationSchedule {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Prompt the user for loan amount, number of years and annual interest rate
System.out.print("Loan Amount: ");
double loanAmount = sc.nextDouble();
System.out.print("Number of Years: ");
int numYears = sc.nextInt();
System.out.print("Annual Interest Rate (in %): ");
double annualInterestRate = sc.nextDouble();
System.out.println(); // Insert a new line
// Print the amortization schedule
printAmortizationSchedule(loanAmount, annualInterestRate, numYears);
}
/**
* Prints amortization schedule for all months.
* #param principal - the total amount of the loan
* #param annualInterestRate in percent
* #param numYears
*/
public static void printAmortizationSchedule(double principal, double annualInterestRate,
int numYears) {
double interestPaid, principalPaid, newBalance;
double monthlyInterestRate, monthlyPayment;
int month;
int numMonths = numYears * 12;
// Output monthly payment and total payment
monthlyInterestRate = annualInterestRate / 12;
monthlyPayment = monthlyPayment(principal, monthlyInterestRate, numYears);
System.out.format("Monthly Payment: %8.2f%n", monthlyPayment);
System.out.format("Total Payment: %8.2f%n", monthlyPayment * numYears * 12);
// Print the table header
printTableHeader();
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;
// Output the data item
printScheduleItem(month, interestPaid, principalPaid, newBalance);
// Update the balance
principal = newBalance;
}
}
/**
* #param loanAmount
* #param monthlyInterestRate in percent
* #param numberOfYears
* #return the amount of the monthly payment of the loan
*/
static double monthlyPayment(double loanAmount, double monthlyInterestRate, int numberOfYears) {
monthlyInterestRate /= 100; // e.g. 5% => 0.05
return loanAmount * monthlyInterestRate /
( 1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12) );
}
/**
* Prints a table data of the amortization schedule as a table row.
*/
private static void printScheduleItem(int month, double interestPaid,
double principalPaid, double newBalance) {
System.out.format("%8d%10.2f%10.2f%12.2f\n",
month, interestPaid, principalPaid, newBalance);
}
/**
* Prints the table header for the amortization schedule.
*/
private static void printTableHeader() {
System.out.println("\nAmortization schedule");
for(int i = 0; i < 40; i++) { // Draw a line
System.out.print("-");
}
System.out.format("\n%8s%10s%10s%12s\n",
"Payment#", "Interest", "Principal", "Balance");
System.out.format("%8s%10s%10s%12s\n\n",
"", "paid", "paid", "");
}
}
That's because you are entered number followed by an enter . So your nextLine method call just reads return key while nextInt just reads integer value ignoring the return key. To avoid this issue:
Just after reading input, you call something like:
int loanAmount=s.nextInt();
s.nextLine();//to read the return key.
Also, it might be a good idea to format your code (identation)

Java JOptionPane Output

Can anybody tell me what I am doing wrong here. I need to calculate some values from user-input into some JOptionPane-input-dialog-boxes, then outputting the answers.
I would greatly appreciate any help I get. Thanks In Advance!
Input
Number of loans to compare (Could be more than 1)
Selling price
Down payment
You will ask the following for each loan they want to compare
Interest rate
Number of years
Processing
You will need to calculate the monthly payment for each scenario listed in part d for the given interest rates and number of years.
Output
Selling price
Down Payment
Loan Amount
List for each scenario
interest
years
payment
Here's my code so far:
package javamortgagecalculator;
import javax.swing.JOptionPane;
import java.util.*;
public class JavaMortgageCalculator {
public static void main(String[] args) {
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
//Convert homeCostString to double
double sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
double downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
double loanAmount = sellingPrice - downPayment;
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] annualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
int counter = 1;
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
double annualInterestRate = Double.parseDouble(annualInterestRateString);
annualInterestRatesArray[i] = (annualInterestRate);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray[i] = (monthlyInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray[i] = (numberOfYears);
//Calculate monthly payment
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPaymentArray[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
//Format to keep totalPayment two digits after the decimal point
totalPayment = (int)(totalPayment * 100) / 100.0;
totalPaymentArray[i] = (totalPayment);
counter++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfLoans; i++) {
sb.append(String.format("\t \t \t \t \t \n", sellingPrice, downPayment, loanAmount, Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray)));
}
String toDisplay=sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
If I was forced, presumably by a large green, and particularly ugly troll masquerading as a programming teacher, to use multiple JOption panes for input and output then here's how I'd tackle the problem. This is meant for your information only... if you hand this in as your own work your teacher will smell a rat, and trolls have google too.
package forums;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/**
* Compares total cost of mortgages (aka ordinary annuity certains)
*/
public class MortgageCalculator
{
public static void main(String[] args)
{
// 1. input
final double price = Enter.aDouble("the purchase of the property");
final double deposit = Enter.aDouble("down payment");
Loan.setPrinciple(price - deposit);
int numLoans = Enter.anInteger("number of loans to compare");
Loan[] loans = new Loan[numLoans];
for ( int i=0; i<numLoans; ++i ) {
loans[i] = new Loan(
Enter.aDouble("Annual interest rate for Loan " + (i+1) + " (eg: 6.75)") / 100.0 / 12.0
, Enter.anInteger("number of years for Loan " + (i+1) + " (eg 20)") * 12
);
}
// 3. Output
final String caption =
"Principle " + Format.money(Loan.getPrinciple())
+ " = Price " + Format.money(price)
+ " - Deposit " + Format.money(deposit);
StringBuilder results = new StringBuilder(64 + numLoans * 64);
results.append("Monthly Rate, Months, Monthly Repayment, Total Repayments\n");
for ( Loan l : loans ) {
results.append(String.format("%5s, %d, %13s, %13s\n"
, Format.percent(l.rate)
, l.periods
, Format.money(l.payment())
, Format.money(l.totalPayment())
));
}
JOptionPane.showMessageDialog(null, results.toString(), caption, JOptionPane.INFORMATION_MESSAGE);
}
static class Format
{
static java.text.Format MONEY = new DecimalFormat("$#,###.##");
static String money(double amount) {
return MONEY.format(amount);
}
static java.text.Format PERCENT = new DecimalFormat("0.###%");
static String percent(double amount) {
return PERCENT.format(amount);
}
static StringBuilder join(String between, Object... values) {
StringBuilder result = new StringBuilder(values.length * 16);
if ( values.length > 0 ) {
result.append(values[0].toString());
for ( int i=1; i<values.length; ++i ) {
result.append(between)
.append(values[i].toString());
}
}
return result;
}
} // end class Format
static class Enter
{
public static int anInteger(String fieldDesc) {
return Integer.parseInt(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
public static double aDouble(String fieldDesc) {
return Double.parseDouble(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
} // end class Enter
} // end class MortgageCalculator
class Loan
{
private static double principle = 34324.121221312432;
final double rate;
final int periods;
static void setPrinciple(double principle) {
if (Loan.principle != 34324.121221312432)
throw new ReadOnlyException("The Principle can't be changed once set.");
Loan.principle = principle;
}
static double getPrinciple() {
return Loan.principle;
}
/**
* Initialises a new loan objects
* #param double rate The interest rate per period, as a percentage.
* eg: 0.00625 is 7.5% per annum.
* #param int periods The number of periods of the loan, typically months.
*/
Loan(double rate, int periods) {
this.rate = rate;
this.periods = periods;
}
// 2. processing
double payment() {
return principle * rate / (1 - 1/Math.pow(1+rate,periods) );
}
double totalPayment() {
return periods * payment();
}
}
class ReadOnlyException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public ReadOnlyException(String message) {
super(message);
}
}
The "list of loans to compare" is represented by an array of Loan objects... I.e: each "loan option" is represented by an instance of the Loan class, which groups all the attributes of a particular loan into one nice tidy "thing" which we can then manipulate as a whole. This a better appraoch than the technique you're using to store loan attributes, which is called "parallel arrays"... and well, umm, it's a bit outdated, in-fact it's got a (greasy) mullet, it's wearing a (too tight) orange safari suit with a (safron pink) head-band... It wasn't a good look in the eighties, and these days, well it's likely to get you beaten-up, arrested, or both; depending on your locale... Basically: We have have better ways now!
The Loan class also has a couple of handy "calculated fields" to do the computations for us. This means that if the WAY we calculate repayments changes for some reason in future, we only have one place to change it, and everything that uses Loans (which could be reading, writing, permuting, totalling, repossessing, or even wholesaling loans) does NOT have to change... they just pick up the change "for free".
In this contrived use-case all our Loans will be for the same ammount, only the interest rates and periods vary... so the Loan class also has a static variable called "principle", which holds THE "common" principle for ALL instances of the Loan class. The principle may only be set once. Any subsequent attempt to set the prinicple will cause a ReadOnlyException to be thrown.
Anyway, I hope that you learn something from seeing another way to tackle some of the sub-problems you may have dicovered while doing this exercise yourself. One tip for the future: Grab your class-mates code for this exercise and read through it... you can learn a LOT from how other people tackle things.
Cheers. Keith.
Now you need to examine the result returned by showMessageDialog(), as shown here.
String.format("\t \t \t \t \t \n", sellingPrice, ...
That's just going to output 5 tabs. You want
String.format("%s %s %s %s %s %n", sellingPrice, ...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}
You haven't told us what the problem is, but I don't think this bit is doing what you want. You're asking the program to print out the entirety of your three arrays every time the loop goes round. Instead, you probably want to access the specific array element for each loan, right? Something like...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
Your JOptionPane.showMessageDialog(null... is inside a for loop. So it will show it as many times as the value of numberOfLoans2 . If you dont want that, move your
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
outside the for-loop.
In your answer printing method the numberOfLoans2 variable is used in two places: in a for loop making the printing happen many times (outer loop) and in a for loop making the mathematic calculation (inner loop). Probably the outer one is with no use, so remove it and the result may be shown once. Remember to remove the ending } on the end of the loop element to keep the structure ok :)

Java Calculator Remove first line

I need to create a Mortgage Calculator for my Java class, and I have been racking my brain all DAY about how to remove the first line of the results. I need to write a 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. Then I need to display the mortgage payment amount and then list the loan balance and interest paid for each payment over the term of the loan.
How do I make it so it calculates the monthly payments starting at month 1 and NOT at month 0? I want to remove the first line $0, $0, $200,000.
import java.text.*; // Import text formatting classes
public class MortgageCalculator {
public static void main(String arguments[]) {
//Variables
double loanAmount = 200000; // Amount borrowed
int loanTerm = 360; // Total months of term
double loanInterest = 0.0575; // Yearly interest in decimal form
double monthlyRate = (loanInterest / 12); //calculate monthly rate
DecimalFormat df = new DecimalFormat("$###,###.00"); //Formatting the results to decimal form
// Assign calculation result to monthlyPayment
double monthlyPayment =
loanAmount *
(monthlyRate * Math.pow((1 + monthlyRate), loanTerm)) /
(Math.pow((1 + monthlyRate), loanTerm) - 1);
//Print Loan Amount, Interest Rate, Loan Term and Monthly Payment
System.out.println("The loan amount is: " +
df.format(loanAmount));
System.out.println("The intrest rate is: " +
loanInterest * 100 + "%");
System.out.println("The term of the loan is: " +
loanTerm / 12 + " years" + "\n");
System.out.println("Monthly Payment: " +
df.format(monthlyPayment) + "\n");
// New variables
double balance = loanAmount;
double monthlyInterest = 0;
double principal = 0;
// display 20 lines of results at one time
// provides columns
System.out.println("\n\n\nPrincipal\tInterest\tBalance");
System.out.println("Payment\t\tPayment\t\tRemaining");
System.out.println("--------- \t--------- \t---------");
// Start Looping
int i;
while (balance > 0) {
for (i = 1; i < 10; i++) {
// Display interest, principal, and balance
System.out.println(df.format(principal) +
"\t\t" +
df.format(monthlyInterest) +
"\t\t" + df.format(balance));
// New calculations
monthlyInterest = (balance * monthlyRate);
principal = (monthlyPayment - monthlyInterest);
balance = (balance - principal);
} // end loop i
//Pauses screen
try {
Thread.sleep(1500);
}
catch(InterruptedException e) {
}
} // end while statement
//Stops loop statement
if (balance <= 0) {
System.out.println("The loan balance is: $0.00");
}
}
}
To remove the first line just do the calculations before the println method is called.
For example:
for (i = 1; i<10; i++) {
// New calculations
monthlyInterest = (balance * monthlyRate);
principal = (monthlyPayment - monthlyInterest);
balance = (balance - principal);
// Display interest, principal, and balance
System.out.println(df.format(principal) + "\t\t" + df.format(monthlyInterest) + "\t\t" + df.format(balance));
} // end loop i
You also need to adjust i in the for-loop accordingly. I think this is what you were asking?
There are various approaches. You coould implement a counter. Your could also check if the amount paid off > 0 before printing
I think the problem lies in the way you're nesting loops. I see that you want to chunk up the output so that it doesn't all dump out at once, but you can easily bring that all into one loop (hint: look at the modulus operator '%'). Then either skip output on the first iteration, using a counter, or check the payment value before printing.
I'm afraid there are more pressing problems than the first funny output line:
$1,156.04 $11.11 $1,161.58
$1,161.58 $5.57 $.00
$1,167.15 $.00 -$1,167.15
$1,172.74 -$5.59 -$2,339.88
$1,178.36 -$11.21 -$3,518.24
$1,184.00 -$16.86 -$4,702.25
$1,189.68 -$22.53 -$5,891.92
$1,195.38 -$28.23 -$7,087.30
$1,201.11 -$33.96 -$8,288.41
$1,206.86 -$39.72 -$9,495.27
The loan balance is: $0.00
There are eight payments too many, and the ending balance is very wrong -- $0.00 when in reality the bank owes the customer nearly ten grand.
I can appreciate that you added the sleep every ten lines for some reasonable reason, but it shouldn't effect the correct calculation of the loan data. I strongly recommend removing the inner loop on i and perhaps sleeping every tenth or twentieth line of output (perhaps using the % operator on that int i that can still be useful :).
Something to consider, if you have enough time before this project is due, is splitting apart your program along a division of duties: Have a function calculate the monthly payment, one function calculate the ratio of principal vs interest, and another routine to print the data to the user. It sounds more complicated this way, but when you need to amend this program in three weeks to provide a graphical output, you'll quickly understand the benefits of keeping display routines separate from computation routines. (This is part of a larger theory of model-view-controller; if you've got time before this is due, please read through the Wikipedia description and try to understand where it would be useful in this program.)

Categories

Resources