Understand basic concept of c programming with more than 100 error free programs. use of header file and different symbols in c programs. for better and complete understanding login to www.eakanchha.com
Modify the bouncing ball example demonstrated/tutorialoutletCleasbyz
FOR MORE CLASSES VISIT
tutorialoutletdotcom
COIS 2240 Assignment#3 Question#1
Modify the bouncing ball example demonstrated in class to include a rectangle as shown in the
figure here: The width of the rectangle should be equal to radius*4, while the height should be equal to the
radius.
This project calls for the modification of the DollarFormat clas.pdfjibinsh
This project calls for the modification of the \"DollarFormat\" class that is in listing 6.14 (p. 424-
425) of the textbook. Access the file named \"DollarFormat.java\" and modify as instructed in
the problem statement. Access the test application to test your modifications when you produce
\"TruncatedDollarFormat\". Start by going into JGRASP and open \"DollarFormat.java\",
rename the class to \"TruncatedDollarFormat\" and save the file as
\"TruncatedDollarFormat.java\", then make the necessary modifications as defined in the
problem statement, save and compile the file, then open the \"TruncatedBankAccount\"
application. Review the TruncatedBankAccount source code to see how each of the methods are
called. DO NOT make any changes to the TruncatedBankAccount application but instead modify
your TruncatedDollarFormat class to accommodate it.
this is the file that needs to be modified
public class TruncatedDollarFormat
{
/**
Displays amount in dollars and cents notation.
Rounds after two decimal places.
Does not advance to the next line after output.
*/
public static void write(double amount)
{
if (amount >= 0)
{
System.out.print(\'$\');
writePositive(amount);
}
else
{
double positiveAmount = -amount;
System.out.print(\'$\');
System.out.print(\'-\');
writePositive(positiveAmount);
}
}
//Precondition: amount >= 0;
//Displays amount in dollars and cents notation. Rounds
//after two decimal places. Omits the dollar sign.
private static void writePositive(double amount)
{
int allCents = (int)(Math.round(amount * 100));
int dollars = allCents / 100;
int cents = allCents % 100;
System.out.print(dollars);
System.out.print(\'.\');
if (cents < 10)
System.out.print(\'0\');
System.out.print(cents);
}
/**
Displays amount in dollars and cents notation.
Rounds after two decimal points.
Advances to the next line after output.
*/
public static void writeln(double amount)
{
write(amount);
System.out.println( );
}
}
this is the test file
import java.util.*;
public class TruncatedBankAccount
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double initialBalance;
double interestRate;
double newBalance; // after 10 years
char answer; // sentinel to repeat or end program
int iteration; // loop counter
do // repeat entire program if user says yes
{
System.out.println(\"Please enter an initial balance \"
+ \"(dollars.cents):\");
initialBalance = keyboard.nextDouble();
System.out.println
(\"Please enter an interest rate in percent \"
+ \"(e.g. 5.25):\");
interestRate = keyboard.nextDouble();
System.out.print(\"In ten years an initial balance of \");
TruncatedDollarFormat.writeln(initialBalance);
System.out.println(\" at an interest rate of \"
+ interestRate + \"% will be worth:\");
// compound annually
newBalance = initialBalance;
for(iteration =1; iteration <= 10; ++iteration)
newBalance = newBalance
+ (interestRate/100) * newBalance;
TruncatedDollarFormat.write(newBalance);
System.out.println(\" compounded annually\");
// compound.
Understand basic concept of c programming with more than 100 error free programs. use of header file and different symbols in c programs. for better and complete understanding login to www.eakanchha.com
Modify the bouncing ball example demonstrated/tutorialoutletCleasbyz
FOR MORE CLASSES VISIT
tutorialoutletdotcom
COIS 2240 Assignment#3 Question#1
Modify the bouncing ball example demonstrated in class to include a rectangle as shown in the
figure here: The width of the rectangle should be equal to radius*4, while the height should be equal to the
radius.
This project calls for the modification of the DollarFormat clas.pdfjibinsh
This project calls for the modification of the \"DollarFormat\" class that is in listing 6.14 (p. 424-
425) of the textbook. Access the file named \"DollarFormat.java\" and modify as instructed in
the problem statement. Access the test application to test your modifications when you produce
\"TruncatedDollarFormat\". Start by going into JGRASP and open \"DollarFormat.java\",
rename the class to \"TruncatedDollarFormat\" and save the file as
\"TruncatedDollarFormat.java\", then make the necessary modifications as defined in the
problem statement, save and compile the file, then open the \"TruncatedBankAccount\"
application. Review the TruncatedBankAccount source code to see how each of the methods are
called. DO NOT make any changes to the TruncatedBankAccount application but instead modify
your TruncatedDollarFormat class to accommodate it.
this is the file that needs to be modified
public class TruncatedDollarFormat
{
/**
Displays amount in dollars and cents notation.
Rounds after two decimal places.
Does not advance to the next line after output.
*/
public static void write(double amount)
{
if (amount >= 0)
{
System.out.print(\'$\');
writePositive(amount);
}
else
{
double positiveAmount = -amount;
System.out.print(\'$\');
System.out.print(\'-\');
writePositive(positiveAmount);
}
}
//Precondition: amount >= 0;
//Displays amount in dollars and cents notation. Rounds
//after two decimal places. Omits the dollar sign.
private static void writePositive(double amount)
{
int allCents = (int)(Math.round(amount * 100));
int dollars = allCents / 100;
int cents = allCents % 100;
System.out.print(dollars);
System.out.print(\'.\');
if (cents < 10)
System.out.print(\'0\');
System.out.print(cents);
}
/**
Displays amount in dollars and cents notation.
Rounds after two decimal points.
Advances to the next line after output.
*/
public static void writeln(double amount)
{
write(amount);
System.out.println( );
}
}
this is the test file
import java.util.*;
public class TruncatedBankAccount
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double initialBalance;
double interestRate;
double newBalance; // after 10 years
char answer; // sentinel to repeat or end program
int iteration; // loop counter
do // repeat entire program if user says yes
{
System.out.println(\"Please enter an initial balance \"
+ \"(dollars.cents):\");
initialBalance = keyboard.nextDouble();
System.out.println
(\"Please enter an interest rate in percent \"
+ \"(e.g. 5.25):\");
interestRate = keyboard.nextDouble();
System.out.print(\"In ten years an initial balance of \");
TruncatedDollarFormat.writeln(initialBalance);
System.out.println(\" at an interest rate of \"
+ interestRate + \"% will be worth:\");
// compound annually
newBalance = initialBalance;
for(iteration =1; iteration <= 10; ++iteration)
newBalance = newBalance
+ (interestRate/100) * newBalance;
TruncatedDollarFormat.write(newBalance);
System.out.println(\" compounded annually\");
// compound.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
Simple array Java code.The “Park-a-lot” parking garage currently o.pdffasttracktreding
Simple array Java code.
The “Park-a-lot” parking garage currently operates without any computerized system. The
management has concerns about inefficiencies of sub-optimal usage of parking space (lost
opportunity/profit). Congestion inside the garage is often caused by drivers searching for vacant
spots. Currently, the management monitors the garage occupancy by having employees walk
around the decks to inspect the occupancy of individual spots.
Now you are hired to develop a more advanced system to track and manage occupancy of a
parking garage and allow customers to find and reserve available parking places.
1. There are 50 parking spaces in total in this parking lot garage
2. The occupancy state of each parking spot: “available,” “reserved,” or “occupied”
3. The customer should be able to check the parking space availability by specifying the desired
date and time interval. If the system responds stating that there are available spots, the customer
should be able to make the parking reservation by data and time
4. The customer should be able to modify their existing reservation(s) before the start time of
their particular reservation.
5. The customer should be able to extend their current occupancy of a parking space only before
their current ending time
Solution
// importing all required libraries
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
/*
The CarFrame class is an implementation of the JFrame and
also contains the main method. Usage:
> java CarFrame
Note that the file carData.txt must be in the same directory as
all compiled code.
*/
public class CarFrame extends JFrame
{
public static JTabbedPane index;
public static CarLot myCarLot;
public CarFrame()
{
// setting window properties
this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
this.setDefaultCloseOperation(3);
this.setTitle(\"Car Park System\");
this.setResizable(false);
Color newColor = new Color(0.2f, 0.1f, 0.8f, 0.1f);
// creating Car Lot object
myCarLot = new CarLot(15, \"carData.txt\");
// building tabbed panel display
index = new JTabbedPane();
index.setBackground(newColor);
final JPanel statusTab = Status.startup();
final JPanel addOrRemoveCarTab = AddOrRemoveCar.startup();
// adding tabs to tabbed panel
index.addTab(\"Lot Status\", statusTab);
index.addTab(\"Add Or Remove Cars\", addOrRemoveCarTab);
// setting content pane
this.getContentPane().add(index);
}
public static void main(String[] args)
{
// initialize frame and set visible
CarFrame main = new CarFrame();
main.setVisible(true);
}
}
class CarLot
{
// class variables
private Vector registeredDrivers;
private Vector parkingStalls;
private String dataFile;
private int maxLotSize;
// constructor
public CarLot(int maxSize, String fileName)
{
registeredDrivers = new Vector();
parkingStalls = new Vector();
maxLotSize = maxSize;
dataFile = fileName;
loadData();
}
public String getDataFileName()
{
return dataFile;
}
public int.
Change to oop formatimport java.util.Scanner;import java.io.;.pdfMAYANKBANSAL1981
Change to oop format
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class Amortization {
/* call values in, set balance and principle. set month to increment until reaching number
provided. use \t to space out result well.
Use PritWriter output instead of System.output to make the notepad file.*/
public static void createReport(String filename, double loan, double interestRate, int years)
throws IOException {
PrintWriter output = new PrintWriter(new FileWriter(filename));
double monthlyPayment = calcPayment(loan, interestRate, years);
int numberOfPayments = getNumberOfPayments(years);
double balance = loan;
output.println("{Monthly Payment}: " + monthlyPayment);
output.println("{Month} \t {Interest} \t {Principal} \t {Balance}");
for (int month = 1; month <= numberOfPayments; month++) {
double interest = balance * (interestRate / 12);
double principal = monthlyPayment - interest;
balance -= principal;
output.printf("%d \t \t %.2f \t \t %.2f \t \t %.2f \\\n", month, interest, principal, balance);
}
output.close();
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.##");
do {
/* Data members */
double loan;
int years;
double interestRate;
/* Get amount, interest rate, and years from the user */
System.out.println("Enter the loan amount: ");
loan = keyboard.nextDouble();
System.out.println("Enter the annual interest rate: ");
interestRate = keyboard.nextDouble() / 100.0;
System.out.println("Enter the years of the loan: ");
years = keyboard.nextInt();
double payment = calcPayment(loan, interestRate, years);
if (payment < 0) {
System.out.println("Invalid input values.");
} else {
System.out.println("Monthly Payment: " + df.format(payment));
int numberOfPayments = getNumberOfPayments(years);
System.out.println("Total Number of Payments: " + numberOfPayments);
try {
createReport("LoanAmortization.txt", loan, interestRate, years);
System.out.println("Report created successfully.");
} catch (IOException e)
{
System.out.println("Error creating report: " + e.getMessage());
}
}
System.out.println("Would you like to run another report? Enter Y for yes or N for no: ");
} while (keyboard.next().equalsIgnoreCase("Y"));
keyboard.close();
}
public static double calcPayment(double loan, double interestRate, int years) {
double term = Math.pow(1 + (interestRate / 12), years * 12);
double payment = (loan * (interestRate / 12) * term) / (term - 1);
return payment;
}
public static int getNumberOfPayments(int years) {
return years * 12; // Assuming monthly payments for the given number of years
}
public static void createReport(String filename) throws IOException {
// Sample implementation to save data to a file
PrintWriter out = new PrintWriter(new FileWriter(filename, true));
out.println("Sample Data");
out.close();
}
}.
The first part of the assignment involves creating very basic GUI co.pdfneerajsachdeva33
The first part of the assignment involves creating very basic GUI controls: a frame, panel, and
slider.
Create a JFrame. Add a title to the frame called Flight Reservation. Set the frame size to 475 by
500 pixels. Create a JPanel inside of the frame. You will be adding all of your UI components to
this JPanel. [6 pts]
Inside of the panel, create a label that says \"Choose Color.\" Right below it, make a slider that
changes the background color of the panel when the slider is moved to a particular color. The
slider values should be RGB color values from 0 to 255 (or black to white). Assume that the
RGB values for red, green, and blue are the same value - for instance: (240, 240, 240). The slider
label\'s text should be replaced with the RGB value that the slider is currently on. [8 pts]
Q2: Add functionality to search for an Itinerary.
Create labels and text fields that allow the user to enter an airline, a source airport, and a
destination airport, as well as the departure time and the arrival time to search for one or more
available flights in an Itinerary. Also, create a ComboBox that will allow the user to select from
a list of flight Itineraries. Each item in the ComboBox represents an Itinerary element, e.g. the
first comboBoxelement is the first Itinerary in the array. [15 pts]
Make sure all text fields have error checking and exception handling for invalid input. For
example, if the user enters an integer as a departure time instead of a String (ie 1200 instead of
12:00 PM), a JOptionPane error message should appear stating, \"Incorrect format for departure
time.\" If the airline they entered is not in the Airline enum, then the option pane should say,
\"Airline unavailable. Please choose a different airline.\" If the airport they entered is not in the
Airport enum, then the option pane should say, \"Unknown city.\" Make sure the times are in
hh:mm format. [8 pts]
Q3: Create a button that says Search and a button that says View. When the user clicks Search,
the combobox will get populated. When the user clicks View, if all the fields are filled out and
have valid input, a JOptionPane with a message dialog should appear stating, \"Flight search
successful!\" The frame should open a new JFrame with the title, \"Flight Information,\" and a
size of 475 by 500 pixels. This frame has the flight information displayed in a JTextArea. [6 pts]
Q4: On the Flight Information frame, you will need to display information for each Flight in the
Itinerary [7 points]:
Airline: Display the airline
Model: The model of the airplane should be generated from the Plane object inside of the Flight
class.
Departure Airport: Display the source airport
Departure City: Display the departure city based on the departure airport (use the
getAirportCity() method you implemented in the Unit 3 assignment to get the airport city)
Destination Airport: Display the destination airport
Destination City: Display the destination city based on the destination airport (use the
g.
You can look at the Java programs in the text book to see how commenanitramcroberts
You can look at the Java programs in the text book to see how comments are added to programs.
Minimal Submitted Files
You are required, but not limited, to turn in the following source files:
Assignment6.java (No need to modify)
Movie.java (No need to modify, modified version from the assignment 4)
Review.java (No need to modify)
CreatePane.java - to be completed
ReviewPane.java - to be completed
You might need to add more methods than the specified ones.
Skills to be Applied:
JavaFX, ArrayList
Classes may be needed:
Button, TextField, TextArea, Label, RadioButton, ListView, and ActionHandler. You may use other classes.
Here is the Assignmnet6.java:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import java.util.ArrayList;
public class Assignment6 extends Application
{
private TabPane tabPane;
private CreatePane createPane;
private ReviewPane reviewPane;
private ArrayList movieList;
public void start(Stage stage)
{
StackPane root = new StackPane();
//movieList to be used in both createPane & reviewPane
movieList = new ArrayList();
reviewPane = new ReviewPane(movieList);
createPane = new CreatePane(movieList, reviewPane);
tabPane = new TabPane();
Tab tab1 = new Tab();
tab1.setText("Movie Creation");
tab1.setContent(createPane);
Tab tab2 = new Tab();
tab2.setText("Movie Review");
tab2.setContent(reviewPane);
tabPane.getSelectionModel().select(0);
tabPane.getTabs().addAll(tab1, tab2);
root.getChildren().add(tabPane);
Scene scene = new Scene(root, 700, 400);
stage.setTitle("Movie Review Apps");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Here is Movie.java:
public class Movie
{
private String movieTitle;
private int year;
private int length;
private Review bookReview;
//Constructor to initialize all member variables
public Movie()
{
movieTitle = "?";
length = 0;
year = 0;
bookReview = new Review();
}
//Accessor methods
public String getMovieTitle()
{
return movieTitle;
}
public int getLength()
{
return length;
}
public int getYear()
{
return year;
}
public Review getReview()
{
return bookReview;
}
//Mutator methods
public void setMovieTitle(String aTitle)
{
movieTitle = aTitle;
}
public void setLength(int aLength)
{
length = aLength;
}
public void setYear(int aYear)
{
year = aYear;
}
public void addRating(double rate)
{
book ...
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);
}
}