First thanks for the help last time I posted it set me on the right track thanks.

Now what I need is to clean up a bit. (this is for the 30 year loan only want to get that to do what I need before creating the same with the other loans) I created a "do" that causes a break if I type in exit. It then takes me back to the main menu but multiple menus, I only need one to show and I can't choose the 30 year loan again unless I choose one of the other loans and then go back.

This is what I would like it to do:

Give me the list of payments for the 30 year loan (this works :))
If I want to leave the list at the end of 12 payments I would like to either return to menu or exit and this returns to menu (this kinda works lol)

and lastly and not very important when my interest rate changes to $1,000 or more it throws off my column (That one is driving me insane I have adjusted everything I can think of.

Here is my code have fun playing with it getting set on the right track again would be great thanks

/*---------------------------------------------------------------------------*/
//                            PROGRAM INFORMATION
//                        Programmer : Mari Dutton
//
//  Date    : (8/14/2010)
//  Name    : MortgageCalculator
//  Filename: MortgageCalculator1.java
//     Purpose : The purpose of this program is to calculate mortgage payments.
//                To calculate and display the customer's monthly mortgage
//            of $200000 at 5.75% interest over 30 years.The program will display
//                360 payments with interest by the Month for 30 years.

//---------------------------------------------------------------------------*/

        import java.text.DecimalFormat;                         //to import decimal format for money
        import java.text.NumberFormat;                               //to import number format
        import java.io.Console;                                         //Calls the class Console for user input and output


    public class MortgageCalculator1                                    // Starts the Class
   {
       public static void main(String[]args) throws Exception                   //declaring main method with thrown Exception
      {

        //Arrays
        double   loanAmount = 200000;                   //Starting Balance of loan
        double[] tMonths = {360,180,84};                        // Array for year term of the Loan
        double[] iRate   = {0.0575,0.055,0.0535};          // Array for interest rate of the Loan

           //Varibles
        double balance;                            //Final balance of each month
        double principal;                          // Principal of each month
        double monthlyInterestPaid;                // Monthly Interest paid with each payment


      //Decimal format
      NumberFormat formatter = new DecimalFormat("00.00");

        //Table display
        int row;
        int maxRows = 12;  //maximum number of rows to display

        //User entry input
        int userEntry;
        String userEntry2 = "Menu";

        //Varibles for calculations per loan type

        double mPayments30;
        double mPayments15;
        double mPayments07;

        //calculating the arrays
        mPayments30 = ((iRate[0]/12) * loanAmount)
        / (1-(Math.pow(1+(iRate[0]/12), (- tMonths[0]))));
        mPayments15 = ((iRate[1]/12) * loanAmount)
        / (1-(Math.pow(1+(iRate[1]/12), (- tMonths[1]))));
        mPayments07 = ((iRate[2]/12) * loanAmount)
        / (1-(Math.pow(1+(iRate[2]/12), (- tMonths[2]))));


        //initializing balance varible
         balance = loanAmount;

        //Calls in the console
         Console c = System.console();

do{

       //Programming infromation
       System.out.println();
       System.out.println("\t\t Mortgage Calculator");
       System.out.println("\t\t -------------------");
       System.out.println("\t\t Programmed by Mari Dutton");
       System.out.println("\t\t Mobile Loan Calculator   ");
       System.out.println("");


       //User imput/instance Menu to determine type of loan
       System.out.println("");
        System.out.println("");
        System.out.println("\t\t Select your Loan. ");
        System.out.println("\t\t ------------------");
        System.out.println("\t\t 1. 30 year with interest at 5.75%.");
        System.out.println("\t\t 2. 15 year with interest at 5.5%  ");
        System.out.println("\t\t 3. 07 year with interest at 5.35% ");
        System.out.println("\t\t 4. Exit");
        System.out.println("");

       //Uner Entry Input from user
       userEntry = (int)System.in.read();


       if (c == null)
       {
            System.err.println("Console Error.");
            System.exit(5);

        }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\

       //=30 year loan
       //If statement to enter User Entry input
       if (userEntry == '1')
       {

    System.out.println("");
       System.out.println("");
       System.out.println("Loan Information:       ");
       System.out.println("========================");
       System.out.println("Loan Amount: $200,000.00");
       System.out.println("Months: " + tMonths[0]);
       System.out.println("Interest% Rate:" + iRate[0]);
       System.out.printf ("Monthly payment amount will be $%.2f",mPayments30);
       System.out.println("");
       System.out.println
    ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
       System.out.println
    ("Payment          Amount         Interest Paid   Principal      Balance");
       System.out.println
    ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");


       for ( row =1; row <= tMonths[0] ; row++)
       {

      //Calculating the Monthly Paid Interest;
      monthlyInterestPaid = (iRate[0]/12) * balance;  //calculates monthly Interest Paid


      //Calculating the Principal
      principal = mPayments30 - monthlyInterestPaid;  //calculates Principal


      //Calculating the Balance
      balance = balance - principal;


      System.out.println("Payment\t"+row+
       "\t"+NumberFormat.getCurrencyInstance().format(mPayments30)+
       "\t"+NumberFormat.getCurrencyInstance().format(monthlyInterestPaid)+
       "\t"+NumberFormat.getCurrencyInstance().format(principal)+
       "\t\t"+NumberFormat.getCurrencyInstance().format(balance));

       if ((row % maxRows) == 0)
       userEntry2 = c.readLine("Press Enter to continue..or type exit to exit. ");


       if(userEntry2.equals("exit")){
       break;
       }
        if(userEntry2.equals("Menu")){

}

    }
 }


       if (userEntry == '2')
       {

     System.out.println("");
      System.out.println("");
      System.out.println("Loan Information:       ");
      System.out.println("========================");
      System.out.println("Loan Amount: $200,000.00");
      System.out.println("Months: " + tMonths[1]);
      System.out.println("Interest% Rate: " + iRate[1]);
      System.out.printf ("Monthly payment amount will be $%.2f", mPayments15);
      System.out.println("");
      System.out.println("");
      System.out.println
  ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println
  ("Payment          Amount         Interest Paid   Principal        Balance");
      System.out.println
  ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

      for ( row =1; row <= tMonths[1]; row++)
      {

      //Calculating the Monthly Paid Interest;
       monthlyInterestPaid = (iRate[1]/12) * balance;  //calculates monthly Interest Paid


     //Calculating the Principal
       principal = mPayments15 - monthlyInterestPaid;  //calculates Principal


     //Calculating the Balance
       balance = balance - principal;


      System.out.println("Payment"  +row+
      ": \t"+NumberFormat.getCurrencyInstance().format (mPayments15) +
      ", \t"+NumberFormat.getCurrencyInstance().format(monthlyInterestPaid) +
      ", \t"+NumberFormat.getCurrencyInstance().format(principal) +
      ", \t"+NumberFormat.getCurrencyInstance().format(balance));

      if ((row % maxRows) == 0)
      userEntry2 = c.readLine("Press Enter to continue... ");
                }

        }

       if (userEntry == '3')
       {
      System.out.println("");
       System.out.println("");
       System.out.println("Loan Information:       ");
       System.out.println("------------------------");
       System.out.println("Loan Amount: $200,000.00");
       System.out.println("Months: " + tMonths[2]);
       System.out.println("Interest% Rate: " + iRate[2]);
       System.out.printf("Monthly payment amount will be $%.2f", mPayments07);
       System.out.println("");
       System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
       System.out.println("Payment          Amount         Interest Paid   Principal        Balance   ");
       System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

       for ( row =1; row <= tMonths[2]; row++)
       {

       //Calculating the Monthly Paid Interest;
       monthlyInterestPaid = (iRate[2]/12) * balance;  //calculates monthly Interest Paid


       //Calculating the Principal
       principal = mPayments07 - monthlyInterestPaid;  //calculates Principal


      //Calculating the Balance
      balance = balance - principal;

      System.out.println("Payment " +row+
      ": \t"+NumberFormat.getCurrencyInstance().format (mPayments07) +
      ", \t"+NumberFormat.getCurrencyInstance().format(monthlyInterestPaid) +
      ", \t"+NumberFormat.getCurrencyInstance().format(principal) +
      ", \t"+NumberFormat.getCurrencyInstance().format(balance));

      if ((row % maxRows) == 0){
      userEntry2 = c.readLine("Thank you Please Press enter to exit ");
   }
  }

}

     }while(userEntry != '4');
    //if(userEntry == '4')
    //{
     System.out.println("\t Exiting the The Mortgage Calculator now. Thank you");
      System.exit(0); //calling exit method
    //}

  }
 }

Recommended Answers

All 5 Replies

One approach would be to break the code up into methods and have a master method that calls the other methods in the order you want them called in.

You need to use a state indicator to remember where you are and what you have done to control what to do next. booleans are often used for this. Or an int with a value telling you what you have done previously and what you need to do next.

SO I would change each section like the one below into a method then make the menu into the "main" method that I would call back to in order to execute and call the other methods, correct?

//=30 year loan
       //If statement to enter User Entry input
       if (userEntry == '1')
       {

    System.out.println("");
       System.out.println("");
       System.out.println("Loan Information:       ");
       System.out.println("========================");
       System.out.println("Loan Amount: $200,000.00");
       System.out.println("Months: " + tMonths[0]);
       System.out.println("Interest% Rate:" + iRate[0]);
       System.out.printf ("Monthly payment amount will be $%.2f",mPayments30);
       System.out.println("");
       System.out.println
    ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
       System.out.println
    ("Payment          Amount         Interest Paid   Principal      Balance");
       System.out.println
    ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");


       for ( row =1; row <= tMonths[0] ; row++)
       {

When you "break" out of a block, you can't return to that point in the code, you can only start from the beginning. Breaking up the method into its functional units is the best solution. Ideally, you want each method to do one thing.
Rather than putting the input in the main method, I'd have that in a method, followed by the calculation (which might well be broken down into several methods) and a method which displays the results.

This would allow you, for example, to later on replace the input and output stages with Swing-based windows and input boxes, which can be made pretty. You might then add in something to graph the life of the loan, and later on you might allow the user to see how the loan changes if you change the payments. All of this is a lot easier to do when the code is modular than when it's one long method.

Later still, you'll find out how to include this class - or elements of it - in a larger financial planning package, leveraging code you've already written rather than rewriting it or copying it verbatim into a new package. This is where you'll see the real advantages of object-oriented programming, but that'll come later.

Thanks for the advice. I was pretty much told that the way my code is it wouldn't work without some serious changes. Thanks,

Well, that may be true. I wasn't about to try to read through it in detail, because it's not very modular and my little brain doesn't want to follow all of that at this hour. :)

If you want to make it more modular, I'd suggest you divide it into logical steps, as above, and write them one at a time. Start with something like this:

public class MortgageCalculator{
  public static void main(String[] args)
  {
    MortgageCalculator mc = new MortgageCalculator();
    mc.getInput();  // do you want to return the values as a "Loan" item, or is  
                    // it better to have a set of global fields for Principal,    
                    // Interest, Duration, etc? This is a design question.

    mc.doTheMath(); // probably break this up into smaller steps
    mc.displayResults();  // show the results of the math, nicely formatted

  }
}

For the start, let your getInput() and doTheMath() methods return dummy values, just pick plausible values and plug them in while you get your output to look tolerable. Then go back and get your math to calculate right, and you can see it come out on the screen looking nice. When your math seems to be working okay, get the input set up so you can test the math method with real numbers (try reasonable values and unreasonable ones, to make sure your code handles the unreasonable ones reasonably, and especially the edge cases where things are mostly reasonable, but close to not)

This is a simplified description of the process, but you get the idea.


And for your display going wonky when you get too many decimal places, you might want to look at the printf() method instead of println(). printf() prints a formatted string - the way the format is defined might take a little experimenting to get right, but it's not fundamentally difficult.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.