IS187 Java Programming I Financials OOP 100 points w 5 Extr
IS187: Java Programming I
Financials - OOP (100 points w/ 5 Extra Credit) 2016
Two related financial processes are the calculation of an Annuity, and the calculation of a simple interest Loan. The final balance of an annuity is based on a consistent, regular monthly deposit that builds value at a specified interest rate; the ‘logical reverse’ of this is a loan, which involves paying a monthly amount to buy down an original principal, which is also charging interest at a specified rate. Both actions involve a monthly amount being adjusted based on an interest rate over a specified term (number of months).
You will build a single ‘view’ form which allows input of the necessary values for either operation, and which then calls an appropriate business logic class depending on analysis choice: one class for calculating an annuity, a different class for calculating a loan payoff. In either operation (Annuity or Loan) the user may request a ‘Full Schedule’ which will produce a second, pop-up form with the month-by-month results of the action.
Part A of the assignment involves building the main view form along with the Annuity business class (including the Annuity schedule). Part B is to create a separate business logic class for the Loan Payment option along with the Loan Payment schedule.
Part A:
The main form will look as follows:
For the annuity, we will assume the Monthly Deposit is made at the beginning of each month, so that deposits earn interest in the month they are made. Thus, a calculated annuity of $100 a month at 6% (annual rate) over 24 months would look as follows:
Note that the Labels on the deposit and result fields will change based on the financial operation selected. After a calculation is complete, the Full Schedule button becomes available. If selected for this annuity example, a popup screen such as the following would appear:
This program must be done in an Object Oriented style. To do this for an Annuity, you will create a class file called Annuity.java, which must have several properties and methods. The required input items are as shown above:
1)The deposit amounts (beginning of each month)
2)The Annual Interest Rate Amount
3)The Term (In Months)
You should write a constructor for this class that accepts parameter values for each of the start values.
You should then code ‘get’ methods in your Annuity.java class which return those same values (i.e., the start values of deposit, rate, and term) and which return all the other calculated values needed to build the output results. The Annuity.java methods to return the values would include:
.getDeposit() – to return the monthly deposit amount
.getIntRate() – to return the annual interest rate
.getTerm() – to return the length of the annuity
.getBegBal(x) – the Beginning balance of month x (x is sent to the method)
.getIntEarned(x) – the interest earned during month x
.getEndBal(x) – the Ending Balance for month x
.getFinalValue() – the Ending Balance after the annuity term is completed
In each case, the ‘x’ that is sent to the method indicates the month for which values are requested. Thus, .getBegBal(2) would return the beginning balance of the second month of the annuity; getIntEarned(3) would be the interest earned in the third month of the annuity, etc.
Note that .getFinalValue() – which doesn’t need a month parameter – would be equal to .getEndBal(annuity.term). But .getFinalValue should be implemented as a separate method. There are no ‘set’ methods in this class, as values are set at instantiation and cannot be changed (a different Annuity object would have to be instantiated for a different scenario).
The pop-up screen is a swing component called a JDialog that is displaying a JTable object that was built to have the required columns (with headings) along with the proper number of rows. Note also that because the table may be longer than the JDialog can accommodate in the default size, the JTable was placed on a JScrollPane in order to give the right-hand scroll bar.
The formulas for the columns are:
1)Beginning Balance = 0 in month 1, previous month ending balance thereafter
2)Deposit = input value from user
3)Interest Earned = (Beginning Balance + Deposit) * (annual interest rate / 12.0)
4)Ending Balance = Beg.Bal + deposit + Interest Earned
The popup window to display the schedule can be a bit confusing when you start out with swing. As noted above, it has the following pieces:
A JTable of 6 columns and ‘t’ rows (where t = the term of the annuity)
A JScrollPane to permit the JTable object to be scrolled up and down
A JDialog object to contain the title and to manage the display.
All of these objects are built in code at the time the ‘Full Schedule’ button is clicked. Building the JTable is done as follows:
First, a ‘model’ for the table must be built. The model simply indicates how many rows and columns will be needed, and what the colmn headings are. For example, code to build a table of 10 rows and 3 columns would be done like this:
String[] cols = { “cName1”, “cName2”, “cName3” };
String[][] t = new String[10][3];
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel(t,cols);
javax.swing.JTable jTbl = new javax.swing.JTable(model);
The DefaultTableModel is first created using the data array t[][] which is based on how big you need the table to be, and the column headings string array cols[]. In our example the column headings are named “cName1”, “cName2”, and “cName3”. The specific instance of the table is then built using the DefaultTableModel object. The specific values in each cell of the table can be set using the .setValueAt(v,r,c) method of the table. Thus, the following line would put the value 1 in the first row and first column cell in the table:
jTbl.setValueOf(1,0,0)
(reference indexes to table rows and columns start at zero, just like arrays do). Code to finish building our pop-up window would be something like the following:
1 javax.swing.JScrollPane sp = new javax.swing.JScrollPane(jTbl);
2 javax.swing.JDialog dg = new javax.swing.JDialog();
3 dg.setTitle(\"Table Example\");
4 dg.add(sp);
5 dg.setSize(500,300);
6 dg.setLocation(150,400);
7 dg.setVisible(true);
Line 1 above builds a scroll pane called ‘sp’ and puts the table in it by sending jTbl to the constructor of the scrollpane. The dialog object is built next, but note that here we don’t send the scroll pane to the constructor of the dialog, but instead we add the pane to the dialog (line 4). This was done after setting the display title on the dialog (line 3). Finally, the size and display location of the dialog is set (lines 5 and 6) and the dialog is displayed by setting the visible property to true (line 7).
As shown in the sample above, the individual cell entries are formatted for content type (e.g., currency, or percentage) but are not right-justified; that is left as the extra credit option.
Part B
For this part of the program you are going to develop and use a class file called ‘Loan’ which calculates the monthly payment required to pay off a simple interest loan (along with all values necessary to build a loan payoff schedule).
The formula for a simple interest loan calculation is fairly straightforward; to determine the monthly payment on such a loan you need the original principal, the monthly interest rate, and the number of months (term) of the loan applied in the following formula:
__ __
Monthly = |Rate + _______Rate________ | * Principal
Payment | ((1 + Rate) ^ Months) - 1 |
|__ __|
In words: Payment = (Rate + (Rate divided by ((1 plus Rate) to the power of the months) minus 1) all times the principal). Rate must be expressed as a per month value (i.e., annual rate in decimal form, divided by 12). A good website that explains this is: www.1728.com/loanform.htm. Remember to consult the java ‘Math’ class, which has such available operations as the ‘power’ method (one number raised to the power of another); the math class is explained in appendix B of the text.
For example, a monthly payment of $437.26 is required to pay back a loan of $5,000 over 12 months at an interest rate of 9.0% per year (annual rate: note that the formula requires rate be converted to monthly form).
As noted above, the main form also changes slightly when a radio button is selected: if Loan is selected, the labels change so that it is clear a Loan Amount is being requested and a Monthly Payment is being calculated. The label changes to the form for an Annuity selection vs. a Loan selection will be accomplished through constants in each class: a constant for “Amount Description” and a constant for “Result Description.” (Constants are created by declaring public static final variables – as will be shown in class).
After entry of the sample values indicated above you would have:
And a full schedule would look as follows:
As the example shows, the column calculations are as follows:
1.Beginning principal = loan amount (month 1) or previous ending balance (all following months).
2.Pmt = Monthly loan payment (value never changes)
3.Interest charge = Beginning principal * monthly interest rate
4.Ending Balance = Beginning Principal + Interest Charge - Monthly Payment
The methods needed in the Loan class are as follows:
1.A constructor which accepts the loan parameters: principal, annual interest rate, and term (in months) and which then fully calculates the loan using appropriately sized arrays to hold all monthly values.
2.‘get’ methods to be able to return any of the 3 starting values; in other words:
a.getPrincipal() to return the original loan amount
b.getIntRate() to return the original annual interest rate
c.getTerm() to return the original term (months of the loan)
3.A ‘get’ method called getMoPmt() which returns the calculated monthly payment for the loan
4.‘get’ methods for each month of the term, which return the array values built inside the constructor, as follows:
a.getBegBal(x) which returns the beginning balance for month ‘x’
b.getIntChg(x) which returns the interest charge for the month ‘x’
c.getEndBal(x) which returns the ending balance for the month ‘x’
In this program no additional ‘set’ methods will be used: once the loan object is instantiated, its original values cannot be changed (a different loan would require a new instantiation of a new loan object).
The Clear function re-sets the form to its original ‘on open’ settings: Annuity is the default (with appropriate labels) and all text boxes are cleared. The Full Schedule button should be disabled and the the focus (cursor) should also be put inside the first text box.
Extra Credit (5 points):
As shown in the examples, the cell entries are not right-justified by default. Getting the cells to right-justify is a little tricky, in that it involves an object called a DefaultTableCellRenderer. You actually set the horizontal alignment on the ‘renderer’ and then you must apply the renderer to the table (or columns of the table, if not all are right-justified). For extra credit points, implement right-justification on all columns and also make sure your percent column displays 3 decimal positions.
E Financial operations File Help Financial operation: Monthly Deposit: Annual Interest Rate (6% 06 Term (Months Value at End of Annuity: Annuity O Loan Calculate Full Schedule Clear Financial operations OX E File Help Financial operation: Monthly Deposit: Annual Interest Rate (6 Term (Months Value at End of Annuity. O Annuity O Loan 100 06 06 Calculate $2,555.91 Full Schedule Clear LUXU E Financial operations File Help Financial Operation: Loan Amount: Annual Interest Rate (6 06 Term (Months Monthly Loan Payment: O Annuity o Loan Calculate Full Schedule ClearSolution
part A-
1 import java.util.Scanner;
 2 class AmortizationProgram{
   
 3 public static void main(String[] args){
 4      double p,iy;
 5 int n;
 6 Scanner sc=new Scanner(System.in);
 7      System.out.print(\"Enter amount of loan:\");
 8 p=sc.nextFloat();
 9 System.out.print(\"Enter interest rate per year:\");
 10 iy=sc.nextFloat();
 11 System.out.print(\"Enter number of years:\");
 12 n=sc.nextInt();    
 13 calAmort(p,iy,n);
   
 14 }
 
 15 public static void calAmort(double p,double iy, int ny){
 16    double newbal;
 17    double im=(iy/12)/100;
 18    int nm=ny*12;
 19   double mp,ip,pp;
 20 int i;
   
 21    mp=p*im*Math.pow(1+im,(double)nm)/(Math.pow(1+im,(double)nm)-1);
  22    printHeader();
 23 //print amortization schedule for all months except the last month
 24    for(i=1;i<nm;i++){   
 25    ip=p*im;//interest paid
 26    pp=mp-ip; //princial paid
 27    newbal=p-pp; //new balance   
 28 printSch(i,p,mp,ip,pp,newbal);
 29    p=newbal; //update old balance
 30 }
 31    //last month
 32 pp=p;
 33 ip=p*im;
 34    mp=pp+ip;
 35 newbal=0.0;
 36 printSch(i,p,mp,ip,pp,newbal);   
   
 37 }
   
 38 public static void printSch(int i,double p,double mp,double ip,double pp,double newbal){
   
 39    System.out.format(\"%-8d%-12.3f%-10.3f%-10.3f%-10.3f%-12.3f\ \",i,p,mp,ip,pp,newbal);
    
 40 }
 
 41 public static void printHeader(){
 42 int i;
 43    System.out.println(\"\ Amortization Schedule for Borrower\");
 44    for(i=0;i<62;i++) System.out.print(\"-\");
 45 System.out.format(\"\ %-8s%-12s%-10s%-10s%-10s%-12s\",\" \",\"Old\",\"Monthly\",\"Interest\",\"Principle\",\"New\",\"Balance\");
 46 System.out.format(\"\ %-8s%-12s%-10s%-10s%-10s%-12s\ \ \",\"Month\",\"Balance\",\"Payment\",\"Paid\",\"Paid\",\"Balance\");
  47 }   
 
 48}
Code Explanation:
 1 include Scanner class to the program. This class is used to get user input from keyboad.
 2 open AmortizationProgram class block.
 3 open the main method.
 4 declare local variable p, and iy to store amount of principle, and interest rate pery year.
 5 delclare local variable n to store the number of years.
 6 create Scanner object sc.
 7-12 allow the user to input amount of loan, interest rate per year, and number of years.
 13 call the calAmort method to calculate monthly payment and print the amortization schedule.
 14 close the main method.
 15 open calAmort method body
 16 declare local variable newbal to store the new balance for each month.
 17 declare local variable im to store the interest rate per month.
 18 declare local variable nm to store the number of months.
 19 declare local variables mp, ip, and pp to store monthly payment, interest paid, and principle paid for each month.
 20 declare local variable i used in for loop iteration.
 21 calculate monthly payment.
 22 print heading text.
 23-30 calculate interest paid(ip), principle paid (pp), old balance (p), new blance (newbal), and print these informaton. The for loop is used to print these informaton from the start month to the end of period except the last month. The for loop has the following form:
 for(start;test;update){
 //code to do something
 }
 The for loop exits when the test result is false. If the test result is true forever, the loop works infinitely.
 The update has to properly define so that the loop will exit when ever you want.
 31-36 calculate interest paid(ip), principle paid (pp), old balance (p), new blance (newbal) for the last month, and print these informaton by calling the printSch method.
 For the last month, it is a special case. The principle paid is set to the new balance of the previous month. The monthly payment is set to sum of principle paid and interest paid, and the new balance is set to zero.
 37 close the calAmort method.
 38 open printSch method body.
 39 define the code to print information.
 40 close the printSch method.
 41 open printHeader method body.
 42-46 define code to print the heading text.
 47 close the printHeader method.
 48 close the AmortizationProgram class.
Part:B
public class LoanPayment{
public static void main(String[] args) {
double termInYears = Double.parseDouble(args[0]);
double Principal = Double.parseDouble(args[1]);
double ratePerYear = Double.parseDouble(args[2]);
double paymentsInTerm = termInYears * 12;
double paymentRate = ratePerYear / 12;
double onePlus = paymentRate + 1;
double singlePaymentTop = paymentRate*Math.pow(onePlus,paymentsInTerm);
double singlePaymentBottom = Math.pow(onePlus,paymentsInTerm)-1;
double singlePayment = Principal*(singlePaymentTop/singlePaymentBottom);
//System.out.println(ratePerYear);
//System.out.println(paymentsInTerm);
//System.out.println(paymentRate);
//System.out.println(singlePaymentTop);
//System.out.println(singlePaymentBottom);
System.out.println(\"If your \"+termInYears+\" year loan is at a rate of \"+ratePerYear+\", that\'s \"+singlePayment+\" per month!\");






