Solved

Java student needs help with amortization code

Posted on 2004-10-04
7
984 Views
Last Modified: 2008-02-01
I have always been told that the first step to programming is to get the code to work, then it can be tidied up. I have written a program that calculates mortgage amortization schedule for three different terms and interest rates, but the code is bulky.

I searched and searched for ideas to condense the if statements. I know I could use some kind of loop there since the code is similar in each case, but I couldn't figure out how to call the array values dynamically.

Also, I reuse the chunk of code the pauses the program and waits for the "Enter" key to be pressed.

Thanks in advance for any help,

Tammi

================

import java.io.* ;
import java.text.NumberFormat;

class AnotherGetInput {

static NumberFormat fmat = NumberFormat.getCurrencyInstance();
      
     public static void main(String args[]) {
          InputStreamReader istream = new InputStreamReader(System.in) ;
          BufferedReader bufRead = new BufferedReader(istream) ;
            
          double loanAmount = 200000;
          double[] interestRate = {5.35/(12*100), 5.5/(12*100), 5.75/(12*100)};
          int[] loanTerm = {7*12, 15*12, 30*12};
            
          double[] monthlyPayment = {
               loanAmount * (interestRate[0]/(1-(Math.pow(1 + interestRate[0], - loanTerm[0])))),
               loanAmount * (interestRate[1]/(1-(Math.pow(1 + interestRate[1], - loanTerm[1])))),
               loanAmount * (interestRate[2]/(1-(Math.pow(1 + interestRate[2], - loanTerm[2]))))
          };
            
          try {
               System.out.println("PLEASE SELECT FROM THE FOLLOWING");
               System.out.println("  (1)  View 7 year mortgage at 5.35%");
               System.out.println("  (2)  View 15 year at 5.5%");
               System.out.println("  (3)  View 30 year at 5.75%");
                  
               String getOption = bufRead.readLine();
                  
               //Convert string to numeric
               int bOption = Integer.parseInt(getOption);
                  
               if(bOption == 1) {
                    for(int period = 1; period <= loanTerm[0]; period++) {
                         double interestPaid = (interestRate[0]) * loanAmount;
                         double principlePaid = monthlyPayment[0] - interestPaid;
                         double endPay = loanAmount - principlePaid;
                         loanAmount = endPay;

                         if(period %20 ==0){
                              System.out.println("Press ENTER to continue...\n");
                              try {
                                   int key = System.in.read();
                              }
                              catch (java.io.IOException ioe) {
                                   ioe.printStackTrace();
                              }
                         }

                         System.out.println(period + "\t\t" + fmat.format(interestPaid) + "\t\t" + fmat.format(principlePaid) + "\t\t" + fmat.format(endPay));
                    }
               }
                  
               if(bOption == 2) {
                    for(int period = 1; period <= loanTerm[1]; period++) {
                         double interestPaid = (interestRate[1]) * loanAmount;
                         double principlePaid = monthlyPayment[1] - interestPaid;
                         double endPay = loanAmount - principlePaid;
                         loanAmount = endPay;

                         if(period %20 ==0){
                              System.out.println("Press ENTER to continue...\n");
                              try {
                                   int key = System.in.read();
                              }
                              catch (java.io.IOException ioe) {
                                   ioe.printStackTrace();
                              }
                         }
                              
                         System.out.println(period + "\t\t" + fmat.format(interestPaid) + "\t\t" + fmat.format(principlePaid) + "\t\t" + fmat.format(endPay));
                    }
               }
                  
               if(bOption == 3) {
                    for(int period = 1; period <= loanTerm[2]; period++) {
                         double interestPaid = (interestRate[2]) * loanAmount;
                         double principlePaid = monthlyPayment[2] - interestPaid;
                         double endPay = loanAmount - principlePaid;
                         loanAmount = endPay;
                              
                         if(period %20 ==0){
                              System.out.println("Press ENTER to continue...\n");
                              try {
                                   int key = System.in.read();
                              }
                              catch (java.io.IOException ioe) {
                                   ioe.printStackTrace();
                              }
                         }
                              
                         System.out.println(period + "\t\t" + fmat.format(interestPaid) + "\t\t" + fmat.format(principlePaid) + "\t\t" + fmat.format(endPay));
                    }
               }
          }
            
          catch (IOException err) {
               System.out.println("Error reading line");
          }
          catch(NumberFormatException err) {
               System.out.println("Error Converting Number");
          }
     }
}
0
Comment
Question by:TammiCole
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12220460
You could do

switch(bOption) {
    case 1:
        // do it
        break;
    case 2:
        // do it
        break;
    // etc
}

Which is a bit tidier
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12220482
But you should really break the procedure up into several methods (functions)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12220487
... where bOption is a parameter to the method(s)
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 6

Expert Comment

by:dorothy2
ID: 12220704
You should write a function which takes two arguments, the annual percentage rate and the amount of the loan. You should have a helper function which converts the annual percentage rate into the one you need for your calculations, and a helper function which converts the time period into the number of months. The helper functions should be described by the main function. You should have a main function that collects the arguments and passes them to the mortgage calculation function.

The goal in programming is to write a generic function which can apply to a variety of situations, including those you don't anticipate at the present -- 13% mortgage rates, 20 year loans, etc. Think of how much code you would have to add now if business conditions change.

BTW - you are using an object oriented language, but writing code as if it were a procedural language. Define a class for the mortgage calculator, and another class that calls it from its main method. That way, if your input screen changes, or you call this function from a web site, you don't have to change the source code that contains the mortgage calculator. The technical term for this is separating the presentation layer from the business logic layer.

Dorothy
0
 
LVL 6

Expert Comment

by:dorothy2
ID: 12220829
My earlier post is a little confusing. You should have a public static void main(String args) function which calls the primary function. The primary function should call the two helper functions I described.

Dorothy
0
 

Author Comment

by:TammiCole
ID: 12220861
Dorothy,

I am brand new to Java and I am working under the constraints of instructor specificaitons for this assignment, hence the "procedural language" approach. I understand what you're saying, but I need to see it in order to understand it. Are there any web sites that you know of that show this approach so that I can see it in action?

Thanks,

Tammi
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 12221320

          double loanAmount = 200000;
          double[] interestRate = {5.35/(12*100), 5.5/(12*100), 5.75/(12*100)};
          int[] loanTerm = {7*12, 15*12, 30*12};          
         
          try {
               System.out.println("PLEASE SELECT FROM THE FOLLOWING");
               System.out.println("  (1)  View 7 year mortgage at 5.35%");
               System.out.println("  (2)  View 15 year at 5.5%");
               System.out.println("  (3)  View 30 year at 5.75%");
               
               String getOption = bufRead.readLine();
               
               //Convert string to numeric
               int bOption = Integer.parseInt(getOption);

               double monthlyPayment = loanAmount * (interestRate[bOption]/(1-(Math.pow(1 + interestRate[bOption], - loanTerm[bOption]))));
               double rate = interestRate[bOption];
               int term = loanTerm[bOption];

               // now use those 3 values to generate your output
               // no if statement required

0

Featured Post

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question