Question

JAVA: amortization table: Hi, I have built this code and in one of my methods: printDetailsToConsole...

JAVA: amortization table:

Hi, I have built this code and in one of my methods: printDetailsToConsole I would like it to print the first 3 payments and the last 3 payments if n is larger than 6 payments.

Please help!

Thank you!!

//start of program
import java.util.Scanner;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.Math;
//345678901234567890123456789012345678901234567890123456789012345678901234567890
/**
* Write a description of class MortgageCalculator here.
*
* @author ()
* @version ()
*/
public class LoanAmortization
{   
/*
*
*/
public static void main(String [] args) {
//declarling necessary values
Scanner s = new Scanner(System.in);
PrintWriter outputStream = outputStream = null;

System.out.println("Hello! This is a loan calculator.");
System.out.println("It will calculate your monthly payments and"
+ " your payments towards your incurred interest and print it to a csv. file");
System.out.println("If you would like to continue please enter"
+ "'y' for yes or 'n' for no");
//try-catch statement
try {
outputStream = new PrintWriter
(new FileOutputStream("mortgagecalculator.csv"));   
}
catch (FileNotFoundException e) {
System.out.println("Error opening csv file");
System.exit(0);
}

char choice = s.next().charAt(0);   
//while loop loops until user enters n when given choice
while ((choice == 'y') || (choice == 'Y')) {
//capture input values from user
getAmortizationTableDetails(s,outputStream);

//ask user if calculate another mortgage
System.out.println("Would you like to enter another mortgage payment?");
System.out.println("Please enter [y] for yes or [n] for no.");

//call to testing method
//testingVariables
choice = s.next().charAt(0);
}
//closing scanner and PrintWriter
s.close();
outputStream.close();
}

/* Method printDetails formats results to 2 decimals and prints it
* to file.
* The loop will ensure that each result will be
* formatted in the way just described and print it to the file.
* The comma after the first statement will ensure that the file seperates
* the results and formats it in a table. It will be possible to open
* the file in Excel this way.
*
* @parameters:
* Scanner s
* PrintWriter outputStream
* int month[]
* double principal[]
* double monthlyPayment[]
* double interestPayment[]
* double remainingBalance[]
* int n
* no return statement
*/
public static void printDetails(Scanner s, PrintWriter outputStream,
int month[], double principal [], double monthlyPayment [],
double interestPayment [], double remainingBalance[], int n ){
outputStream.println
("Month, Principal, Monthly Payment, Interest Payment, Remaining Balance");
for (int i = 0; i < n; i++) {
//print to file
outputStream.print(month[i] + ", ");
outputStream.printf("%.2f,",principal [i]);
outputStream.printf("%.2f,",monthlyPayment[i]);
outputStream.printf("%.2f,",interestPayment[i]);
outputStream.printf("%.2f\n",remainingBalance[i]);
}
}

public static void printDetailsToConsole(Scanner s,
int month[], double principal [], double monthlyPayment [],
double interestPayment [], double remainingBalance[], int n ){
System.out.println
("Month, Principal, Monthly Payment, Interest Payment, Remaining Balance");
for (int i = 0; i < n; i++) {
//print to file
System.out.print(month[i] + ", ");
System.out.printf("%.2f,",principal [i]);
System.out.printf("%.2f,",monthlyPayment[i]);
System.out.printf("%.2f,",interestPayment[i]);
System.out.printf("%.2f\n",remainingBalance[i]);

if (n < 6) {
//
System.out.print(month[i] + ", ");
System.out.printf("%.2f,",principal [i]);
System.out.printf("%.2f,",monthlyPayment[i]);
System.out.printf("%.2f,",interestPayment[i]);
System.out.printf("%.2f\n",remainingBalance[i]);

}
else {
//printing the first 3 payments and the last 3 payments
  
System.out.print(month[i] + ", ");
System.out.printf("%.2f,",principal [i]);
System.out.printf("%.2f,",monthlyPayment[i]);
System.out.printf("%.2f,",interestPayment[i]);
System.out.printf("%.2f\n",remainingBalance[i]);
  
  
}

  
}
}

/*
*
*/
public static void getAmortizationTableDetails
(Scanner s, PrintWriter outputStream)
{
//asking user for input
System.out.println("Enter your loan amount.");
double loanAmount = s.nextDouble();
System.out.println("Enter your annual interest rate (in percent).");
double interestRate = s.nextDouble(); //in percent;
interestRate = interestRate / 100; //to convert to decimal
interestRate = interestRate/12;
System.out.println("Enter the term of your loan in years");
int termOfLoan = s.nextInt();
int n = termOfLoan * 12; //n = number of payments
int size = (int) (termOfLoan * 12); //size for array

//creating and declaring arrays
double principal [] = new double [size];
double monthlyPayment[] = new double [size];
double interestPayment[] = new double [size];
int month[] = new int [size];
double remainingBalance [] = new double [size];
double startingBalance = loanAmount;

for (int i = 0; i < n; i++) {
month[i] = i+1;
monthlyPayment[i] =
calculateMonthlyPayment(loanAmount, interestRate, n);

//calling method to fill interestPayment array
interestPayment[i] = calculateInterest(startingBalance, interestRate);
principal [i] = startingBalance;
startingBalance = startingBalance - (monthlyPayment[i] - interestPayment[i]);
remainingBalance[i] = startingBalance;
}
//call to method affordableCheck
affordableCheck(loanAmount, interestRate, n);

//call to method printDetails
printDetails
(s, outputStream, month, principal, monthlyPayment,
interestPayment, remainingBalance, n);
printDetailsToConsole
(s, month, principal, monthlyPayment,
interestPayment, remainingBalance, n);
}

/*
*
*/
public static void affordableCheck (double loanAmount, double interestRate, int n){
Scanner s = new Scanner(System.in);
System.out.println("If you would like to know if you can afford this loan"
+ " please enter your annual income.");
double income = s.nextDouble();
double annualPayment = (calculateMonthlyPayment(loanAmount, interestRate, n) * 12);
if (annualPayment > income) {
System.out.println("You won't be able to afford this loan.");
}
else {
System.out.println("Congratulations! You can afford this loan.");
}
}

/* Method calculateMonthlyPayment calculates the monthly payment of the loan
* for the user.
*   
* @parameters: double loanAmount
* double interestRate
* int n
* @return: double monthlyPayment
*/
public static double calculateMonthlyPayment(double loanAmount, double interestRate, int n) {
double monthlyPayment;
monthlyPayment = (loanAmount * (interestRate * (Math.pow((1 + interestRate),n))))/
((Math.pow((1 + interestRate), n)) - 1);

//returns solution for monthlyPayment
return monthlyPayment;
}

/*
*
*/
public static double calculateInterest(double startingBalance, double interestRate) {
double interestAmount;
interestAmount = startingBalance * interestRate;
return interestAmount;
}

/* testingVariables tests if methods used in program will
* return correct values.
*
* Method testingVariables tests if the calculation for the interest and the
* monthlyPayment produce the accurate output.
* no parameters
* no return statement
*/
public static void testingVariables() {
System.out.printf("The interest should be $10. %.2f \n" , calculateInterest(1000,0.01));
System.out.printf("The monthly payment should be $13.22. %.2f \n", calculateMonthlyPayment(1000, 0.1, 120));
}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//start of program

import java.util.Scanner;

import java.io.FileOutputStream;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.lang.Math;

//345678901234567890123456789012345678901234567890123456789012345678901234567890

/**

* Write a description of class MortgageCalculator here.

*

* @author ()

* @version ()

*/

public class LoanAmortization {

/*

*

*/

public static void main(String[] args) {

// declarling necessary values

Scanner s = new Scanner(System.in);

PrintWriter outputStream = outputStream = null;

System.out.println("Hello! This is a loan calculator.");

System.out.println("It will calculate your monthly payments and"

+ " your payments towards your incurred interest and print it to a csv. file");

System.out.println("If you would like to continue please enter" + "'y' for yes or 'n' for no");

// try-catch statement

try {

outputStream = new PrintWriter(new FileOutputStream("mortgagecalculator.csv"));

} catch (FileNotFoundException e) {

System.out.println("Error opening csv file");

System.exit(0);

}

char choice = s.next().charAt(0);

// while loop loops until user enters n when given choice

while ((choice == 'y') || (choice == 'Y')) {

// capture input values from user

getAmortizationTableDetails(s, outputStream);

// ask user if calculate another mortgage

System.out.println("Would you like to enter another mortgage payment?");

System.out.println("Please enter [y] for yes or [n] for no.");

// call to testing method

// testingVariables

choice = s.next().charAt(0);

}

// closing scanner and PrintWriter

s.close();

outputStream.close();

}

/*

* Method printDetails formats results to 2 decimals and prints it to file. The

* loop will ensure that each result will be formatted in the way just described

* and print it to the file. The comma after the first statement will ensure

* that the file seperates the results and formats it in a table. It will be

* possible to open the file in Excel this way.

*

* @parameters: Scanner s PrintWriter outputStream int month[] double

* principal[] double monthlyPayment[] double interestPayment[] double

* remainingBalance[] int n no return statement

*/

public static void printDetails(Scanner s, PrintWriter outputStream, int month[], double principal[],

double monthlyPayment[], double interestPayment[], double remainingBalance[], int n) {

outputStream.println("Month, Principal, Monthly Payment, Interest Payment, Remaining Balance");

for (int i = 0; i < n; i++) {

// print to file

outputStream.print(month[i] + ", ");

outputStream.printf("%.2f,", principal[i]);

outputStream.printf("%.2f,", monthlyPayment[i]);

outputStream.printf("%.2f,", interestPayment[i]);

outputStream.printf("%.2f\n", remainingBalance[i]);

}

}

public static void printDetailsToConsole(Scanner s, int month[], double principal[], double monthlyPayment[],

double interestPayment[], double remainingBalance[], int n) {

System.out.println("Month, Principal, Monthly Payment, Interest Payment, Remaining Balance");

if (n >= 6) {

for (int i = 0; i < 3; i++) {

// print to file

System.out.print(month[i] + ", ");

System.out.printf("%.2f,", principal[i]);

System.out.printf("%.2f,", monthlyPayment[i]);

System.out.printf("%.2f,", interestPayment[i]);

System.out.printf("%.2f\n", remainingBalance[i]);

}

for (int i = n-3; i<n; i++) {

// print to file

System.out.print(month[i] + ", ");

System.out.printf("%.2f,", principal[i]);

System.out.printf("%.2f,", monthlyPayment[i]);

System.out.printf("%.2f,", interestPayment[i]);

System.out.printf("%.2f\n", remainingBalance[i]);

}

} else {

for (int i = 0; i < n; i++) {

// print to file

System.out.print(month[i] + ", ");

System.out.printf("%.2f,", principal[i]);

System.out.printf("%.2f,", monthlyPayment[i]);

System.out.printf("%.2f,", interestPayment[i]);

System.out.printf("%.2f\n", remainingBalance[i]);

}

}

}

/*

*

*/

public static void getAmortizationTableDetails(Scanner s, PrintWriter outputStream) {

// asking user for input

System.out.println("Enter your loan amount.");

double loanAmount = s.nextDouble();

System.out.println("Enter your annual interest rate (in percent).");

double interestRate = s.nextDouble(); // in percent;

interestRate = interestRate / 100; // to convert to decimal

interestRate = interestRate / 12;

System.out.println("Enter the term of your loan in years");

int termOfLoan = s.nextInt();

int n = termOfLoan * 12; // n = number of payments

int size = (int) (termOfLoan * 12); // size for array

// creating and declaring arrays

double principal[] = new double[size];

double monthlyPayment[] = new double[size];

double interestPayment[] = new double[size];

int month[] = new int[size];

double remainingBalance[] = new double[size];

double startingBalance = loanAmount;

for (int i = 0; i < n; i++) {

month[i] = i + 1;

monthlyPayment[i] = calculateMonthlyPayment(loanAmount, interestRate, n);

// calling method to fill interestPayment array

interestPayment[i] = calculateInterest(startingBalance, interestRate);

principal[i] = startingBalance;

startingBalance = startingBalance - (monthlyPayment[i] - interestPayment[i]);

remainingBalance[i] = startingBalance;

}

// call to method affordableCheck

affordableCheck(loanAmount, interestRate, n);

// call to method printDetails

printDetails(s, outputStream, month, principal, monthlyPayment, interestPayment, remainingBalance, n);

printDetailsToConsole(s, month, principal, monthlyPayment, interestPayment, remainingBalance, n);

}

/*

*

*/

public static void affordableCheck(double loanAmount, double interestRate, int n) {

Scanner s = new Scanner(System.in);

System.out

.println("If you would like to know if you can afford this loan" + " please enter your annual income.");

double income = s.nextDouble();

double annualPayment = (calculateMonthlyPayment(loanAmount, interestRate, n) * 12);

if (annualPayment > income) {

System.out.println("You won't be able to afford this loan.");

} else {

System.out.println("Congratulations! You can afford this loan.");

}

}

/*

* Method calculateMonthlyPayment calculates the monthly payment of the loan for

* the user.

*

* @parameters: double loanAmount double interestRate int n

*

* @return: double monthlyPayment

*/

public static double calculateMonthlyPayment(double loanAmount, double interestRate, int n) {

double monthlyPayment;

monthlyPayment = (loanAmount * (interestRate * (Math.pow((1 + interestRate), n))))

/ ((Math.pow((1 + interestRate), n)) - 1);

// returns solution for monthlyPayment

return monthlyPayment;

}

/*

*

*/

public static double calculateInterest(double startingBalance, double interestRate) {

double interestAmount;

interestAmount = startingBalance * interestRate;

return interestAmount;

}

/*

* testingVariables tests if methods used in program will return correct values.

*

* Method testingVariables tests if the calculation for the interest and the

* monthlyPayment produce the accurate output. no parameters no return statement

*/

public static void testingVariables() {

System.out.printf("The interest should be $10. %.2f \n", calculateInterest(1000, 0.01));

System.out.printf("The monthly payment should be $13.22. %.2f \n", calculateMonthlyPayment(1000, 0.1, 120));

}

}

===============================================
See Code,Thanks and let me know if its fine


PLEASE COMMENT if there is any concern.

if (n 6) 86 87 for (int i-0; i<3; i++) I // print to file System.out.print (month[i] + ", ) System.out.printf("%.2f,", principal [i]); System.out.printf("%.2f,'', monthlyPayment [i]); System. out . printf("%.2f,", înterestPayment[i]); System.out.printf("%.2f\n", remainingBalance [i]); 89 90 91 92 93 94 95 96 97 98 for (inti n-1; i>-(n-3); i--) //print to file System.out.print (month[i] + ", "); System.out.printf("%.2f,", principal [i]); System.out.printf("%.2f,", monthlyPayment [i]); System.out.printf("%.2f,", înterestPayment[i]); System.out.printfc"%.2fNn", remainingBalance [i]); 100 101 102 103 104 105 106 107 108 109 110 } else i for (int i 0; i < n; i++) { // print to file System.out.print(monthCi]+ ", "); System.out.printf("%.2f,'', principa [i]); System.out.printf("%.2f,", monthlyPayment [i]); System.out.printf("%.2f,", interestPayment[i]); System.out.printf("%.2f\n", remainingBalance [i]); 112 113 114 115 116 118

Add a comment
Know the answer?
Add Answer to:
JAVA: amortization table: Hi, I have built this code and in one of my methods: printDetailsToConsole...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables...

    import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables int creditScore; double loanAmount,interestRate,interestAmount; final double I_a = 5.56,I_b = 6.38,I_c = 7.12,I_d = 9.34,I_e = 12.45,I_f = 0; String instructions = "This program calculates annual interest\n"+"based on a credit score.\n\n"; String output; Scanner input = new Scanner(System.in);// for receiving input from keyboard // get input from user System.out.println(instructions ); System.out.println("Enter the loan amount: $"); loanAmount = input.nextDouble(); System.out.println("Enter the credit score: "); creditScore...

  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • NETBEANS JAVA BANK PROGRAM (TAKE SCREENSHOTS FROM NETBEANS INCLUDING OUTPUT PLEASE) Display the accounts for the...

    NETBEANS JAVA BANK PROGRAM (TAKE SCREENSHOTS FROM NETBEANS INCLUDING OUTPUT PLEASE) Display the accounts for the current displayed customer PLEASEEEEEEEEEE package bankexample; import java.util.UUID; public class Customer { private UUID id; private String email; private String password; private String firstName; private String lastName;    public Customer(String firstName, String lastName, String email, String password) { this.id = UUID.randomUUID(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String...

  • Help check why the exception exist do some change but be sure to use the printwriter...

    Help check why the exception exist do some change but be sure to use the printwriter and scanner and make the code more readability Input.txt format like this: Joe sam, thd, 9, 4, 20 import java.io.File; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class Main1 { private static final Scanner scan = new Scanner(System.in); private static String[] player = new String[622]; private static String DATA = " "; private static int COUNTS = 0; public static...

  • This is my code but my overtime calculation is wrong and I cant figure out how...

    This is my code but my overtime calculation is wrong and I cant figure out how to round to two decimal places import java.util.Scanner; public class HourlyWage { public static void main(String[] args) { //Variables double totalWage; double totalOvertimePay; double totalPay; String name; double overtimeHours = 0.0; double hoursWorked = 0.0; double hourlyWage = 0.0; Scanner keyboard = new Scanner(System.in); System.out.println("Please enter your name "); name = keyboard.next(); System.out.println("Please enter your hourly wage "); hourlyWage = keyboard.nextDouble(); System.out.println("How many hours...

  • Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class...

    Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class Car {    private int year; private String model; private String make; int speed; public Car(int year, String model, String make, int speed) { this.year = year; this.model = model; this.make = make; this.speed = speed; } public Car() { } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getModel() { return model; }...

  • Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called...

    Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called "jobMap" in my main method instead of calling them in the 2 classes? Also, is there a way to avoid the "Suppress Warning" portion in RoundRobin.java? I haven't been able to find a way for some reason. This is a job scheduling program, so the output should give the same values. To run: javac Main.java, java Main 5jobs.txt . txt file will be provided...

  • Computer Science - Java Explain the code step by step (in detailed order). Also explain what...

    Computer Science - Java Explain the code step by step (in detailed order). Also explain what the program required. Thanks 7 import java.io.File; 8 import java.util.Scanner; 9 import java.util.Arrays; 10 import java.io.FileNotFoundException; 12 public class insertionSort 13 14 public static void insertionSort (double array]) 15 int n -array.length; for (int j-1; j < n; j++) 17 18 19 20 21 double key - array[j]; int i-_1 while ( (i > -1) && ( array [i] > key array [i+1] -...

  • /** this is my code, and I want to invoke the method, doubleArraySize() in main method....

    /** this is my code, and I want to invoke the method, doubleArraySize() in main method. and I need to display some result in cmd or terminal. also, I have classes such as Average and RandomN needed for piping(pipe). please help me and thank you. **/ import java.util.Scanner; public class StdDev { static double[] arr; static int N; public static void main(String[] args) { if(args.length==0){ arr= new double[N]; Scanner input = new Scanner(System.in); int i=0; while(input.hasNextDouble()){ arr[i] = i++; }...

  • In the code shown above are two parts of two different exercises. HOW WE CAN HAVE...

    In the code shown above are two parts of two different exercises. HOW WE CAN HAVE BOTH OF THEM ON THE SAME CLASS BUT SO WE CAN RECALL them threw different methods. Thank you. 1-First exercise import java.util.Scanner; public class first { public static int average(int[] array){    int total = 0;    for(int x: array)        total += x;    return total / array.length;    } public static double average(double[] array){    double total = 0;    for(double x: array)        total += x;    return total /...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT