Java Calculator Remove first line - java

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.)

Related

How do I turn a meal order code into stats that a human can read in java?

Pretty simple question, even though it looks long.
I am supposed to write a java code that accepts an input of something like "021250040625Pat John" and turn it into 02 adult meals at 12.50 each (first 6 numbers say that) 4 child meals at 06.25 each (second six) name is Pat John.
I have to total it and add discount but I can do all that, 𝐈 𝐣𝐮𝐬𝐭 𝐝𝐨𝐧'𝐭 𝐤𝐧𝐨𝐰 𝐡𝐨𝐰 𝐭𝐨 𝐫𝐞𝐚𝐝 𝐢𝐧𝐝𝐢𝐯𝐢𝐝𝐮𝐚𝐥 𝐧𝐮𝐦𝐛𝐞𝐫𝐬 𝐟𝐫𝐨𝐦 𝐚 𝐬𝐭𝐫𝐢𝐧𝐠. Any and all help welcome, I'm new to java but understand the basics. Just need help with reading those individual numbers and letters in the input code.
I already have the basics of the code laid out and this// (result is a placeholder)
Scanner userInput = new Scanner(System.in);
System.out.print("Enter your order code: ");
orderCode = userInput.nextDouble();
System.out.println("Name: " + result);
System.out.println("Adult meals: " + result);
System.out.println("Child meals: " + result);
System.out.println("Subtotal: " + result);
System.out.println("15% Discount: " + result);
System.out.println("Total: " + result);
You want to use Scanner#nextLine() to get the order code, and String#substring(int beginIndex, int endIndex) to get the individual numbers. You can convert the numbers from String to int using Integer.praseInt(String s):
Scanner userInput = new Scanner(System.in);
System.out.print("Enter your order code: ");
// Get the entire code using Scanner.nextLine() instead of Scanner.nextDouble()
String code = userInput.nextLine();
// Get the first two characters (the adult meals)
int adultMeals = Integer.parseInt(code.substring(0, 2));
// Get the next four characters separated by a period (the price)
double price = Double.parseDouble(code.substring(2, 4) + "." + code.substring(4, 6));
// Get the next two characters (the child meals)
int childMeals = Integer.parseInt(code.substring(7, 8));
// Get the next four characters separated by a period (the child price)
double childPrice = Double.parseDouble(code.substring(8, 10) + "." + code.substring(10, 12));
/*
* To calculate the subtotal, multiple the adult price by the number of adult
* meals, and the child price by the number of child meals, then add the two
* together.
*/
double subtotal = (price * adultMeals) + (childPrice * childMeals);
// The discount is 15% of the subtotal
double discount = subtotal * 0.15;
// Subtract the discount to get the total
double total = subtotal - discount;
String name = code.substring(12);
System.out.println("Name: " + name);
System.out.println("Adult meals: " + adultMeals);
System.out.println("Child meals: " + childMeals);
System.out.println("Subtotal: " + subtotal);
System.out.println("15% Discount: " + discount);
System.out.println("Total: " + total);
What I would suggest is to read the meal code as a String, then use substring method in order to cut it up in sections. This will work as long as your meal codes follow the same scheme. You will end up with small strings that you can parse as integers or doubles. There are a few ways to handle the lack of decimal points in the prices, like dividing by the amount of precision you want (100 for 2 decimals).
The adult meal part would look something like this:
int numAdultMeals = Integer.parseInt(orderCode.substring(0, 2));
double adultMealPrice = Double.parseDouble(orderCode.substring(2, 6)) / 100.0;
check out javas substring method... you can then divide the input into different variables.
alternatively, store the input to a char array, then grab the items you want from that array using there indexes.
It appears that your input is positional, meaning the first two characters are the quantity, the next four the price, etc.
If that is the case you can use String.substring to divide the string (as in substring(0,2) to get the first two characters). Then use Double.parseDouble() to convert them into numbers (or maybe Integer.parseInt() for the quantities).
You will need to divide the prices by 100 after converting them.

confusion about while loop

I'm just starting to learn my first programming language as of yesterday, so I'm writing simple test programs from my java book.
What I'm attempting to do is to have a user enter a static monthly investment and how many months they will be saving for, then display their total savings after that period of time.
when I compile the program it says that in system.out.println at the end of the program that total has not been initialized. I have tried initializing total in just the loop but I figured that would put the scope of it in the loop So I tried initializing it at the top and figured it runs through the loop until the condition is met but doesn't go back to the top of the program to put the value back in so I make another variable at the end of the loop to hold the total at the end of the loop. What's Wrong with my logic
thank you for the help!
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 0){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
thanks everyone for the help it now compiles however it seems when going through the math it doesn't take in account the first month of savings for example if I do $100 each month its total at the end is %502.08 which I don't believe is right
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount = 0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 1){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
monthCountDown = monthCountDown - 1;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
set totalAmount = 0,that will instialize it, let me know if this fixes the problem
when you declare it declare it like this double totalAmount = 0;
try 2 steps:
double totalAmount; ==> double totalAmount = 0;
while (monthCountDown > 0); ==> while (monthCountDown-- > 0);
Hava a nice day, my friend.
This problem is a little intricate although the compiler (javac program) provides following helpful message:
Compound.java:33: error: variable totalAmount might not have been
initialized double total = totalAmount;
What could be happening you may wonder. The easy answer is to go to line 20 in your program and initialize the value of totalAmount to 0. Then your program would compile.
The reason the compiler does that is rather complicated, but you can reason about it this way:
What if, just what if the while loop did not get run even once (as written, in your program, opposite is happening as you will soon figure out that you are forgetting something about the loop variable)? Then Java would execute the (next) statement double total = totalAmount; and the way this assignment statement is executed is roughly like this:
read the variable on the right side of =, that is totalAmount in a temporary location
transfer the contents of that location to the memory for the variable on the left side of =, i.e. total.
Now, Java does not like to read a local variable's (such as totalAmount) value that is never written to because it may contain some garbage value. When you initialize it with a value like 0, this problem goes away.
First of all there is no need of using intitalAmount and totalAmount. Because each time you are inserting same values to them. Secondly if you make
monthCountdown > 1
then it will count a month less. Because suppose you are counting for 6 months. Now for monthCountdown > 1 the loop will iterate for 5 times and calculate interest for 5 times. Which I believe is not the logic you want to implement.
So it should be,
monthCountdown > 0
Lastly your mathematical logic is not correct because each time you are calculating the interest on the monthly value and adding it with the previous balance. But it should be like each time interest should be calculated on the total current balance.
while (monthCountDown > 0){
totalAmount = ( amountSavedMonthly + totalAmount ) * monthlyInterestRate;
}
Please let me know if any concern.
First of all, it isn't necessarily the case that totalAmount will not be initialized. However, depending on the user input, it is POSSIBLE that totalAmount will not have been initialized, which will then throw an exception when the program attempts to assign the value of totalAmount to total. To avoid this, you need to ensure that totalAmount gets initialized, which is easy to do. When you declare totalAmount, simply assign 0 as its value.
You also have a problem with your while loop. Because the value of monthCountDown is never changed within the loop, there is no way for the condition monthCountDown > 0 to become false. I'm assuming you intended for monthCountDown to be reduced by 1 each time the loop is run, so you should include monthCountDown--; within the loop to prevent it from becoming an infinite loop.
Initialize totalAmount to 0...
Make in while condition greater than 1..
cricket-007 is right about initializing totalamount = 0; But it looks like your while loop keeps going. Try this!
changed your arrow key from > to <, on the while loop
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount =0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown < 0) {
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}

How would you write Junit tests for this code?

Im new to java and practising my coding, how would I write some Junit tests for this code without changing it? I wanted to write some Junits to see if the output is correct. Could someone provide one such example?
Any help is greatly appreciated.
package returnOnInvestment;
import java.util.Scanner;
/**
This program compares CD /Investment plans input by the year
broken down by the requirements below:
This program creates a table of compound interest investment growth over time
Broken down by: a) year b) balance at end of year
Finance formula of A= P(1+ r/n)^n*t is used:
A = Future Value | P = Initial Investment
r = annual interest rate |n = times interest is compounded/year
t = years invested
*/
public class BestInvesment
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String bestBankName = "";
double bestGrowth = 0;
boolean done = false;
while(!done)
{
System.out.print("Plan name (one word, Q to quit): ");
String bankName = in.next();
if (bankName.equals("Q"))
{
done = true;
}
else
{
System.out.print("Please enter your principal investment: ");
final double PRINCIPAL_INVESTMENT = in.nextDouble();
System.out.print("Please enter the annual interest rate: ");
double iRate = in.nextDouble();
System.out.print("Please enter number of times interest is compounded per year: ");
final double INCREMENT = 1;//in.nextDouble();
System.out.print("Enter number of years: ");
int nyears = in.nextInt();
iRate = iRate/100; System.out.println("iRate:" + iRate);
//Print the table of balances for each year
for (int year = 1; year <= nyears; year++)
{
double MULTIPLIER = INCREMENT * year;
System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
double interest = 1 + (iRate/INCREMENT);
double balance = PRINCIPAL_INVESTMENT;
double growth = balance * Math.pow(interest, MULTIPLIER);
growth = growth - PRINCIPAL_INVESTMENT;
balance = balance + growth;
System.out.printf("Year: %2d Interest Earned: $%.2f\t Ending Balance: $%.2f\n", year, growth, balance);
if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
{
bestBankName = bankName; // bestBankName = bankName
bestGrowth = growth; // mostGrow = growth
}
System.out.println("Earning with this option: " + growth);
}
}
}
System.out.println("Best Growth: " + bestBankName);
System.out.println("Amount Earned: " + bestGrowth);
}
}
As it is, this code is very difficult to test, which it is a symptom of some design smells.
One thing to realize is that you are severely violating the Single Responsibility Principle.
Your code which is just one blob is doing the following things:
printing stuff to console
getting input from the user
doing some calculation
coordinating all this
Since this is in the realm of practicing, I would heavily refactor the code into separate classes. Those then should be easily testable, especially the one doing the calculation, since it will have just some simple methods where you can pass some values as arguments, and check the results
For testing the input and output classes note that you can change System.in and System.out to point to your own implementations, so you can create those to facilitate testing. You might want to look into a mocking framework for this (e.g. Mockito) but it is perfectly possible without such framework.

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 :)

Need help Java amortization table

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;

Categories

Resources