SlideShare une entreprise Scribd logo
1  sur  3
Télécharger pour lire hors ligne
/*
* This program is a loan payment calculator. It accepts a loan amount and
* number of years in text boxes from the user, then displays a table showing
* monthly payments and total payments for various interest rates, from 5% to 8%
* in increments of 0.125%, when a button is clicked. This allows the user to
* compare the effects of the various interest rates on the loan amount and
* period.
*
* Author: Bill Rutherford
*
*/
import javafx.application.Application;
import javafx.geometry.*;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
public class CalculateLoanPayments extends Application {
private TextField tfLoanAmount = new TextField();
private TextField tfNumberOfYears = new TextField();
private TextArea taPaymentTable = new TextArea();
private Tooltip ttLoanAmount = new Tooltip(
"Loan amount must be a nonnegative money amount");
private Tooltip ttNumberOfYears = new Tooltip(
"Number of years must be a nonnegative integer");
@Override
public void start(Stage primaryStage) {
final int SCENE_WIDTH = 555;
final int SCENE_HEIGHT = 250;
Button btShowTable = new Button("Show Table");
// Set text field properties
tfLoanAmount.setPrefColumnCount(10);
tfNumberOfYears.setPrefColumnCount(3);
// Create a pane for text fields and button
HBox inputPane = new HBox(10);
inputPane.setPadding(new Insets(10, 10, 10, 10));
inputPane.setAlignment(Pos.CENTER_LEFT);
inputPane.getChildren().addAll(new Label("Loan Amount "), tfLoanAmount,
new Label("tNumber of Years "), tfNumberOfYears, btShowTable);
// Set the button off to the right
HBox.setMargin(btShowTable, new Insets(0, 0, 0, SCENE_WIDTH - 505));
// Set text area properties
// Switch to a monospaced font; it's easier to get the columns to
// line up with it
taPaymentTable.setFont(Font.font("Lucida Console", 14));
taPaymentTable.setPrefRowCount(27);
taPaymentTable.setPrefColumnCount(60);
taPaymentTable.setEditable(false);
// Create a pane to hold the controls and text area
BorderPane mainPane = new BorderPane();
mainPane.setTop(inputPane);
mainPane.setCenter(new ScrollPane(taPaymentTable));
// Set event handlers
btShowTable.setOnAction(e -> showTable());
tfLoanAmount.setOnKeyTyped(e -> {
// Restore normal text color
tfLoanAmount.setStyle("-fx-text-fill: black");
// Turn off tooltip display
Tooltip.uninstall(tfLoanAmount, ttLoanAmount);
});
tfNumberOfYears.setOnKeyTyped(e -> {
tfNumberOfYears.setStyle("-fx-text-fill: black");
Tooltip.uninstall(tfNumberOfYears, ttNumberOfYears);
});
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, SCENE_WIDTH, SCENE_HEIGHT);
primaryStage.setTitle("Exercise 16_13");
primaryStage.setScene(scene);
primaryStage.show();
}
/** Create and display payment table */
public void showTable() {
int numberOfYears = getNumberOfYearsFromText();
double loanAmount = getLoanAmountFromText();
if (loanAmount >= 0.0 && numberOfYears >= 0) { // input is valid
// Declare table and create table header
StringBuilder table = new StringBuilder(
"Interest Ratet Monthly PaymenttTotal Payment");
// Create table body
for (Double interestRate = 5.0; interestRate <= 8.0;
interestRate += 0.125) {
String line = String.format("n%-5stt %-21.2f%-20.2f",
interestRate.toString(),
round(calculateMonthlyPayment(interestRate, loanAmount,
numberOfYears)),
round(calculateTotalPayment(interestRate, loanAmount,
numberOfYears)));
table.append(line);
}
// Display table
taPaymentTable.setText(table.toString());
}
// else do nothing; wait for the user to correct the errors
}
/** Get and validate the loan amount from the text field */
public double getLoanAmountFromText() {
double amount = 0.0;
boolean amountValid;
try {
amount = Double.parseDouble(tfLoanAmount.getText());
amountValid = (amount >= 0.0);
}
catch (NumberFormatException ex) {
amountValid = false;
}
if (amountValid)
return amount;
else { // set error indicators
tfLoanAmount.setStyle("-fx-text-fill: red");
// Set tooltip to display when the mouse is hovered over the
// text box
Tooltip.install(tfLoanAmount, ttLoanAmount);
// At least display a red cursor when the field is blank
// Display red text without the blue highlighting when it isn't
if (tfLoanAmount.getText().equals(""))
tfLoanAmount.requestFocus();
return -1.0; // return an error code
}
}
/** Get and validate the number of years from the text field */
public int getNumberOfYearsFromText() {
int years = 0;
boolean yearsValid;
try {
years = Integer.parseInt(tfNumberOfYears.getText());
yearsValid = (years >= 0);
}
catch (NumberFormatException ex) {
yearsValid = false;
}
if (yearsValid)
return years;
else { // set error indicators
tfNumberOfYears.setStyle("-fx-text-fill: red");
// Set tooltip to display when the mouse is hovered over the
// text box
Tooltip.install(tfNumberOfYears, ttNumberOfYears);
// At least display a red cursor when the field is blank
// Display red text without the blue highlighting when it isn't
if (tfNumberOfYears.getText().equals(""))
tfNumberOfYears.requestFocus();
return -1; // return an error code
}
}
/** Return monthly payment */
public double calculateMonthlyPayment(double interestRate,
double loanAmount, int numberOfYears) {
double monthlyInterestRate = interestRate / 1200;
return loanAmount * monthlyInterestRate / (1 - 1 /
Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
}
/** Return total payment */
public double calculateTotalPayment(double interestRate,
double loanAmount, int numberOfYears) {
return calculateMonthlyPayment(interestRate, loanAmount, numberOfYears) *
numberOfYears * 12;
}
/** Round a money amount to the nearest cent */
// By creating this method and using it the way I did, I got the numbers
// to match the example in the book
public double round(double amount) {
return (int)(amount * 100) / 100.0;
}
public static void main(String[] args) {
launch(args);
}
}

Contenu connexe

Tendances

Input output statement in C
Input output statement in CInput output statement in C
Input output statement in CMuthuganesh S
 
Bcsl 033 data and file structures lab s1-1
Bcsl 033 data and file structures lab s1-1Bcsl 033 data and file structures lab s1-1
Bcsl 033 data and file structures lab s1-1Dr. Loganathan R
 
Conditional & Cast Operator
Conditional & Cast OperatorConditional & Cast Operator
Conditional & Cast OperatorJeeban Mishra
 
Basic of c programming www.eakanchha.com
Basic of c programming www.eakanchha.comBasic of c programming www.eakanchha.com
Basic of c programming www.eakanchha.comAkanchha Agrawal
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and OutputSabik T S
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingSabik T S
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9Rumman Ansari
 
C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2Rumman Ansari
 
Intro to c chapter cover 1 4
Intro to c chapter cover 1 4Intro to c chapter cover 1 4
Intro to c chapter cover 1 4Hazwan Arif
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branchingSaranya saran
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
 
Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletCleasbyz
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in cSaranya saran
 
Bcsl 033 data and file structures lab s4-2
Bcsl 033 data and file structures lab s4-2Bcsl 033 data and file structures lab s4-2
Bcsl 033 data and file structures lab s4-2Dr. Loganathan R
 
Bcsl 033 data and file structures lab s3-3
Bcsl 033 data and file structures lab s3-3Bcsl 033 data and file structures lab s3-3
Bcsl 033 data and file structures lab s3-3Dr. Loganathan R
 
Loop control structure
Loop control structureLoop control structure
Loop control structureKaran Pandey
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’eShikshak
 

Tendances (20)

Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
Bcsl 033 data and file structures lab s1-1
Bcsl 033 data and file structures lab s1-1Bcsl 033 data and file structures lab s1-1
Bcsl 033 data and file structures lab s1-1
 
Conditional & Cast Operator
Conditional & Cast OperatorConditional & Cast Operator
Conditional & Cast Operator
 
Basic of c programming www.eakanchha.com
Basic of c programming www.eakanchha.comBasic of c programming www.eakanchha.com
Basic of c programming www.eakanchha.com
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
week-18x
week-18xweek-18x
week-18x
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9
 
C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2
 
Intro to c chapter cover 1 4
Intro to c chapter cover 1 4Intro to c chapter cover 1 4
Intro to c chapter cover 1 4
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
C programming
C programming C programming
C programming
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
week-4x
week-4xweek-4x
week-4x
 
Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutlet
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
 
Bcsl 033 data and file structures lab s4-2
Bcsl 033 data and file structures lab s4-2Bcsl 033 data and file structures lab s4-2
Bcsl 033 data and file structures lab s4-2
 
Bcsl 033 data and file structures lab s3-3
Bcsl 033 data and file structures lab s3-3Bcsl 033 data and file structures lab s3-3
Bcsl 033 data and file structures lab s3-3
 
Loop control structure
Loop control structureLoop control structure
Loop control structure
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 

Similaire à CalculateLoanPayments

This project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdfThis project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdfjibinsh
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfarihantmum
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
Simple array Java code.The “Park-a-lot” parking garage currently o.pdf
Simple array Java code.The “Park-a-lot” parking garage currently o.pdfSimple array Java code.The “Park-a-lot” parking garage currently o.pdf
Simple array Java code.The “Park-a-lot” parking garage currently o.pdffasttracktreding
 
Change to oop formatimport java.util.Scanner;import java.io.;.pdf
Change to oop formatimport java.util.Scanner;import java.io.;.pdfChange to oop formatimport java.util.Scanner;import java.io.;.pdf
Change to oop formatimport java.util.Scanner;import java.io.;.pdfMAYANKBANSAL1981
 
Gift-VT Tools Development Overview
Gift-VT Tools Development OverviewGift-VT Tools Development Overview
Gift-VT Tools Development Overviewstn_tkiller
 
Scala+swing
Scala+swingScala+swing
Scala+swingperneto
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 
The first part of the assignment involves creating very basic GUI co.pdf
The first part of the assignment involves creating very basic GUI co.pdfThe first part of the assignment involves creating very basic GUI co.pdf
The first part of the assignment involves creating very basic GUI co.pdfneerajsachdeva33
 
You can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenYou can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenanitramcroberts
 
Creating an Uber Clone - Part III.pdf
Creating an Uber Clone - Part III.pdfCreating an Uber Clone - Part III.pdf
Creating an Uber Clone - Part III.pdfShaiAlmog1
 
Justin trimmer cop2000 5-week 2_super supermarket pay calculator
Justin trimmer cop2000 5-week 2_super supermarket pay calculatorJustin trimmer cop2000 5-week 2_super supermarket pay calculator
Justin trimmer cop2000 5-week 2_super supermarket pay calculatorWintur
 
project4-ast.DS_Storeproject4-astast.c#include symbolTa.docx
project4-ast.DS_Storeproject4-astast.c#include symbolTa.docxproject4-ast.DS_Storeproject4-astast.c#include symbolTa.docx
project4-ast.DS_Storeproject4-astast.c#include symbolTa.docxwkyra78
 

Similaire à CalculateLoanPayments (20)

This project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdfThis project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdf
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdf
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Simple array Java code.The “Park-a-lot” parking garage currently o.pdf
Simple array Java code.The “Park-a-lot” parking garage currently o.pdfSimple array Java code.The “Park-a-lot” parking garage currently o.pdf
Simple array Java code.The “Park-a-lot” parking garage currently o.pdf
 
Change to oop formatimport java.util.Scanner;import java.io.;.pdf
Change to oop formatimport java.util.Scanner;import java.io.;.pdfChange to oop formatimport java.util.Scanner;import java.io.;.pdf
Change to oop formatimport java.util.Scanner;import java.io.;.pdf
 
Gift-VT Tools Development Overview
Gift-VT Tools Development OverviewGift-VT Tools Development Overview
Gift-VT Tools Development Overview
 
Scala+swing
Scala+swingScala+swing
Scala+swing
 
Flowcharting
FlowchartingFlowcharting
Flowcharting
 
Flowcharts
FlowchartsFlowcharts
Flowcharts
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
The first part of the assignment involves creating very basic GUI co.pdf
The first part of the assignment involves creating very basic GUI co.pdfThe first part of the assignment involves creating very basic GUI co.pdf
The first part of the assignment involves creating very basic GUI co.pdf
 
You can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenYou can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commen
 
Java Week10 Notepad
Java Week10   NotepadJava Week10   Notepad
Java Week10 Notepad
 
T
TT
T
 
Creating an Uber Clone - Part III.pdf
Creating an Uber Clone - Part III.pdfCreating an Uber Clone - Part III.pdf
Creating an Uber Clone - Part III.pdf
 
Calculator
CalculatorCalculator
Calculator
 
Justin trimmer cop2000 5-week 2_super supermarket pay calculator
Justin trimmer cop2000 5-week 2_super supermarket pay calculatorJustin trimmer cop2000 5-week 2_super supermarket pay calculator
Justin trimmer cop2000 5-week 2_super supermarket pay calculator
 
project4-ast.DS_Storeproject4-astast.c#include symbolTa.docx
project4-ast.DS_Storeproject4-astast.c#include symbolTa.docxproject4-ast.DS_Storeproject4-astast.c#include symbolTa.docx
project4-ast.DS_Storeproject4-astast.c#include symbolTa.docx
 
3. control statement
3. control statement3. control statement
3. control statement
 

CalculateLoanPayments

  • 1. /* * This program is a loan payment calculator. It accepts a loan amount and * number of years in text boxes from the user, then displays a table showing * monthly payments and total payments for various interest rates, from 5% to 8% * in increments of 0.125%, when a button is clicked. This allows the user to * compare the effects of the various interest rates on the loan amount and * period. * * Author: Bill Rutherford * */ import javafx.application.Application; import javafx.geometry.*; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.scene.text.Font; public class CalculateLoanPayments extends Application { private TextField tfLoanAmount = new TextField(); private TextField tfNumberOfYears = new TextField(); private TextArea taPaymentTable = new TextArea(); private Tooltip ttLoanAmount = new Tooltip( "Loan amount must be a nonnegative money amount"); private Tooltip ttNumberOfYears = new Tooltip( "Number of years must be a nonnegative integer"); @Override public void start(Stage primaryStage) { final int SCENE_WIDTH = 555; final int SCENE_HEIGHT = 250; Button btShowTable = new Button("Show Table"); // Set text field properties tfLoanAmount.setPrefColumnCount(10); tfNumberOfYears.setPrefColumnCount(3); // Create a pane for text fields and button HBox inputPane = new HBox(10); inputPane.setPadding(new Insets(10, 10, 10, 10)); inputPane.setAlignment(Pos.CENTER_LEFT); inputPane.getChildren().addAll(new Label("Loan Amount "), tfLoanAmount, new Label("tNumber of Years "), tfNumberOfYears, btShowTable); // Set the button off to the right HBox.setMargin(btShowTable, new Insets(0, 0, 0, SCENE_WIDTH - 505)); // Set text area properties // Switch to a monospaced font; it's easier to get the columns to // line up with it taPaymentTable.setFont(Font.font("Lucida Console", 14)); taPaymentTable.setPrefRowCount(27); taPaymentTable.setPrefColumnCount(60); taPaymentTable.setEditable(false); // Create a pane to hold the controls and text area BorderPane mainPane = new BorderPane(); mainPane.setTop(inputPane); mainPane.setCenter(new ScrollPane(taPaymentTable)); // Set event handlers btShowTable.setOnAction(e -> showTable()); tfLoanAmount.setOnKeyTyped(e -> { // Restore normal text color tfLoanAmount.setStyle("-fx-text-fill: black");
  • 2. // Turn off tooltip display Tooltip.uninstall(tfLoanAmount, ttLoanAmount); }); tfNumberOfYears.setOnKeyTyped(e -> { tfNumberOfYears.setStyle("-fx-text-fill: black"); Tooltip.uninstall(tfNumberOfYears, ttNumberOfYears); }); // Create a scene and place it in the stage Scene scene = new Scene(mainPane, SCENE_WIDTH, SCENE_HEIGHT); primaryStage.setTitle("Exercise 16_13"); primaryStage.setScene(scene); primaryStage.show(); } /** Create and display payment table */ public void showTable() { int numberOfYears = getNumberOfYearsFromText(); double loanAmount = getLoanAmountFromText(); if (loanAmount >= 0.0 && numberOfYears >= 0) { // input is valid // Declare table and create table header StringBuilder table = new StringBuilder( "Interest Ratet Monthly PaymenttTotal Payment"); // Create table body for (Double interestRate = 5.0; interestRate <= 8.0; interestRate += 0.125) { String line = String.format("n%-5stt %-21.2f%-20.2f", interestRate.toString(), round(calculateMonthlyPayment(interestRate, loanAmount, numberOfYears)), round(calculateTotalPayment(interestRate, loanAmount, numberOfYears))); table.append(line); } // Display table taPaymentTable.setText(table.toString()); } // else do nothing; wait for the user to correct the errors } /** Get and validate the loan amount from the text field */ public double getLoanAmountFromText() { double amount = 0.0; boolean amountValid; try { amount = Double.parseDouble(tfLoanAmount.getText()); amountValid = (amount >= 0.0); } catch (NumberFormatException ex) { amountValid = false; } if (amountValid) return amount; else { // set error indicators tfLoanAmount.setStyle("-fx-text-fill: red"); // Set tooltip to display when the mouse is hovered over the // text box Tooltip.install(tfLoanAmount, ttLoanAmount); // At least display a red cursor when the field is blank // Display red text without the blue highlighting when it isn't if (tfLoanAmount.getText().equals("")) tfLoanAmount.requestFocus();
  • 3. return -1.0; // return an error code } } /** Get and validate the number of years from the text field */ public int getNumberOfYearsFromText() { int years = 0; boolean yearsValid; try { years = Integer.parseInt(tfNumberOfYears.getText()); yearsValid = (years >= 0); } catch (NumberFormatException ex) { yearsValid = false; } if (yearsValid) return years; else { // set error indicators tfNumberOfYears.setStyle("-fx-text-fill: red"); // Set tooltip to display when the mouse is hovered over the // text box Tooltip.install(tfNumberOfYears, ttNumberOfYears); // At least display a red cursor when the field is blank // Display red text without the blue highlighting when it isn't if (tfNumberOfYears.getText().equals("")) tfNumberOfYears.requestFocus(); return -1; // return an error code } } /** Return monthly payment */ public double calculateMonthlyPayment(double interestRate, double loanAmount, int numberOfYears) { double monthlyInterestRate = interestRate / 1200; return loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); } /** Return total payment */ public double calculateTotalPayment(double interestRate, double loanAmount, int numberOfYears) { return calculateMonthlyPayment(interestRate, loanAmount, numberOfYears) * numberOfYears * 12; } /** Round a money amount to the nearest cent */ // By creating this method and using it the way I did, I got the numbers // to match the example in the book public double round(double amount) { return (int)(amount * 100) / 100.0; } public static void main(String[] args) { launch(args); } }