?
Solved

2 code problems

Posted on 2009-12-26
71
Medium Priority
?
633 Views
Last Modified: 2013-11-23
Help! I have written my code but there are two errors. I have made various corrections but the yield is the same. Here are the two errors.
First,  after I enter the amount 2000000 and No, there should be a display which there is but the numbers are not correct. Instead of the example below there is interest rates where the years should be. The correct version should look like this:

Loan Term      Interest Rate        Mortgage Payment
7 years          5.35%                   $2859.79
15 years        5.5%                     $1634.17
30 years        5.75%                   $1167.15

My second error is that after the above display, the user should enter 2000000 and Yes.
Yet, the columns go without stopping and display only zeros.
There should be only 7 columns displayed. Each column should display a number.
Column 1 -- Payment number
Column 2 -- the first loan balance
Column 3 -- the first loan interest paid
Column 4 -- the second loan balance
Column 5 -- the second loan interest paid
Column 6 -- the third loan balance
Column 7 -- the third loan interest paid

The display should appear like this:
1       198031.88       891.67     199282.50       916.67    199791.19    958.33
2       196054.98       882.89     198561.71       913.38    199581.38    957.33
3       194069.27       874.08     197837.62       910.07    199370.56    956.33

Thanks is advance!

Here is my code:

/**
 Programming 420 Week 7 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Week7 {

//declare variables
double principle = 0;
//principle of loan is determined by user

double payment = 0;
//payment is calculated below according to user's principle

int [] term = {7, 15, 30};                                                

//declare array of term of loans
double [] rate = {.0535, .055, .0575};                                          

//delcare array of interest rates
boolean goodNumber = false;                                                

//declares goodNumber as boolean

                        

            DecimalFormat f = new DecimalFormat ("$###,###.00");                        

      //formats to 2 decimals places



      private boolean showReport = false;

      /**
       * Default constructor
       */
      public Week7() {
      }

      /**
       * The main function for the mortgage calculator
       *
       * @param args
       * @throws IOException
       */
      public static void main(String[] args) throws IOException {
            // Create an object of Week7 to process the Mortgage
            Week7 mortgageCalculator = new Week7();
            mortgageCalculator.acceptInput();
            mortgageCalculator.process();
      }

      /**
       * Function for the calculation of the years in the loan payment
       *
       * @param years
       * @param interestRate
       * @return
       */
      private double MonthlyInterest(double amount, double interestRate) {
            // Declaring Variables for interest on the loan
            double dMonthlyInterest = 0.0;
            // Calculation for monthly interest
            dMonthlyInterest = (amount / 12) * (interestRate / 100);
            return dMonthlyInterest;
      }

      /**
       * function for the calculation of the interest into the loan payment
       *
       * @param amount
       * @param interestRate
       * @param term
       * @return
       */
      private double monthlyPayment(double amount, double interestRate,
                  double term) {
            // Declaring Variables for interest on the loan
            double dMonthlyPayment = 0.0;
            // Calculation for monthly interest
            dMonthlyPayment = (amount * interestRate)
                        * (1 - Math.pow(1 / (1 + interestRate), term));
            if (amount <= 0 || dMonthlyPayment <= 0) {
                  dMonthlyPayment = 0.0;
            }
            return dMonthlyPayment;
      }

      /**
       * function for the calculation of the monthy loan balance
       *
       * @param amount
       * @param monthlyPayment
       * @return
       */
      private double monthlyBalance(double amount, double monthlyPayment) {
            // Declaring Variables for monthly loan balance
            double dMonthlyBalance = 0.0;
            // Calculations for monthly loan balance
            dMonthlyBalance = (amount - monthlyPayment);
            if (dMonthlyBalance <= 0) {
                  dMonthlyBalance = 0.0;
            }
            return dMonthlyBalance;
      }

      /**
       * Function to show the Mortagage Schedule
       */
      private void showMortagageSchedule() {
            // output for month to years
            for (int i : iTerm)
                  System.out.println(String.format(
                              "An %1$s-month loan equals a %2$s-year loan.", i, i

/ 12));

            System.out.println();
            System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
                        "Term", "Payment", "Monthly Interest", "Monthly Principle",
                        "Balance"));
            // Loop for the varying Mortgage Rates and Payments

            // Month counter
            for (int i = 1; i <= 360; i++) {
                  for (int p = 0; p <= 2; p++) {
                        // Calculation for the monthly mortgage payment
                        dRate = dInterest[p] / 1200;
                        switch (p) {
                        case 0:
                              dPayment = monthlyPayment(dAmount, dInterest[p] /

12,
                                          iTerm[p]);
                              dMonthlyInterest1 = MonthlyInterest(dAmount,
                                          dInterest[p] / 12);
                              dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
                              dMonthlyBalance1 = monthlyBalance(dAmount,
                                          dMonthlyPrinciple);
                              dAmount = dMonthlyBalance1;
                              break;
                        case 1:
                              dPayment = monthlyPayment(dAmount, dInterest[p] /

12,
                                          iTerm[p]);
                              dMonthlyInterest2 = MonthlyInterest(dAmount,
                                          dInterest[p] / 12);
                              dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
                              dMonthlyBalance2 = monthlyBalance(dAmount,
                                          dMonthlyPrinciple);
                              dAmount = dMonthlyBalance2;
                              break;
                        case 2:
                              dPayment = monthlyPayment(dAmount, dInterest[p] /

12,
                                          iTerm[p]);
                              dMonthlyInterest3 = MonthlyInterest(dAmount,
                                          dInterest[p] / 12);
                              dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
                              dMonthlyBalance3 = monthlyBalance(dAmount,
                                          dMonthlyPrinciple);
                              dAmount = dMonthlyBalance3;
                              break;
                        }

                  }
                  // Output for the loan information and the monthly payment
                  // System.out.println("Your Monthly Payment for a " + iTerm[p] +
                  // " month loan of $200,000 at " + dInterest[p] + "% is:" +
                  // twoDigits.format(dPayment));
                  System.out
                              .println(String
                                          .format(
                                                      "%1$s\t%2$10.2f\t%

3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f",
                                                      i,

dMonthlyBalance1, dMonthlyInterest1,
                                                      dMonthlyBalance2,

dMonthlyInterest2,
                                                      dMonthlyBalance3,

dMonthlyInterest3));
            }
      }

      /**
       * Function to accept input from user and set it to class level variables
       */
      public void acceptInput() {

            double principle = 0;
            // begins loop for input error checking
            boolean goodNumber = false; // declares goodNumber as boolean
            String userChoice = "No";

            // open up standard input
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            // while loop lets try and catch statements determine if an exception
            // requires user to reinput
            while (!goodNumber) {
                  // try statement in case of exception such as user entering a

string
                  try {
                        // informs user to enter amount of desired loan
                        System.out
                                    .println("Please enter the loan amount as a

number: ");
                        // delcares Scanner object
                        Scanner input = new Scanner(br);
                        principle = input.nextDouble();
                        if (principle <= 0.0) {
                              System.out
                                          .println("Error:  Loan Amount must

be greater than $0.00");
                              continue; // This causes the loop to continue

without
                              // executing statements after this code
                        }
                        // Set the local variable to the class level variable
                        this.dAmount = principle;
                        // set goodNumber to true if no exception to let program
                        // continue
                        goodNumber = true;
                  } catch (Exception e) {
                        System.out
                                    .println("Error: The entered number is

invalid or not a number. Please enter a valid number.");
                  }
            }

            System.out
                        .println("Do you see want to view the amortization 7 column

table or not? Respond with Yes/No and click <ENTER> key:");
            try {
                  userChoice = br.readLine();
                  if (userChoice == null || "".equals(userChoice.trim())) {
                        System.out
                                    .println("No input provided. By default the

report will not be shown ");
                  } else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
                              .equalsIgnoreCase(userChoice))) {
                        System.out
                                    .println("Invalid input provided. By

default the report will not be shown ");
                  } else if ("Yes".equalsIgnoreCase(userChoice)) {
                        showReport = true;
                  }
                  // The else condition of userChoice="No" is already covered with
                  // intitialization
            } catch (IOException ioe) {
                  System.out.println("IOException while reading input: "
                              + ioe.getMessage());
            }
      }

      /**
       * Function to process the output
       */
      public void process() {

            DecimalFormat f = new DecimalFormat("$###,###.00");
            double payment;

            // if statement to ensure user enters amount greater than 0
            if (this.dAmount > 0)

            {
                  // informs user of desired loan amount
                  System.out.println("\nLoan Amount = " + f.format(this.dAmount));

                  // displays calculator headings
                  System.out
                              .println

("\n\n*****************************************************");
                  System.out.println("* Loan Term " + "\tInterest Rate"
                              + "\tMortgage Payment    *");
                  System.out
                              .println

("*****************************************************");
                  // begins loop to determine terms, rates, and payments
                  for (int i = 0; i < dInterest.length; i++) {
                        // calculations to determine payment
                        payment = this.dAmount
                                    * ((dInterest[i] / 12) / (1 - Math.pow(
                                                1 / (1 + (dInterest[i] /

12)),
                                                ((iTerm[i]) * 12))));
                        // displays term in years, interest rates, and payments
                        System.out.println((dInterest[i]) + "  years" + "\t"
                                    + ((dInterest[i]) * 100) + "%" + "\t\t"
                                    + f.format(payment));

                  }

                  System.out.println();

                  if (this.showReport) {
                        // Call function to show the mortgage schedule
                        showMortagageSchedule();
                  }
            }
      }
}
0
Comment
Question by:coldjava
  • 35
  • 19
  • 17
71 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 26126278
How and where is dPayment defined? Same question for a number of other variables?
0
 

Author Comment

by:coldjava
ID: 26127806
Phoffric --

 Thanks for the reply. Is that where the problem is, in a lack of dPayment?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26128475
Hi coldjava,
I get compiler errors because for the code that you submitted, there are many variables that have no definition. But since you are able to get results from your program, it appears that what you posted is not entirely what your project consists of. So, could you close your project builder, and then submit all the java code files (using the File attachment approach), and then we'll have the same files as you are working with.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 32

Expert Comment

by:phoffric
ID: 26128542
Or, if you only have one java file, you can paste it into the "Code" section below the comment box. I have copied one piece of code from your post. Now the compiler knows that dMonthlyPayment is a double. But for other variables such as dPayment, dMonthlyInterest1, dMonthlyInterest2, etc., you reference these variables, but did not define them as you did for dMonthlyPayment.
            // Declaring Variables for interest on the loan
            double dMonthlyPayment = 0.0;

Open in new window

0
 

Author Comment

by:coldjava
ID: 26128705
Phoffric --

Thanks for your help.

 I am attaching my original code. The correct version should look like the example below. Thanks again.

The correct version should look like this:

Loan Term      Interest Rate        Mortgage Payment
7 years          5.35%                   $2859.79
15 years        5.5%                     $1634.17
30 years        5.75%                   $1167.15

My second error is that after the above display, the user should enter 2000000 and Yes.
Yet, the columns go without stopping and display only zeros.
There should be only 7 columns displayed. Each column should display a number.
Column 1 -- Payment number
Column 2 -- the first loan balance
Column 3 -- the first loan interest paid
Column 4 -- the second loan balance
Column 5 -- the second loan interest paid
Column 6 -- the third loan balance
Column 7 -- the third loan interest paid

The display should appear like this:
1       198031.88       891.67     199282.50       916.67    199791.19    958.33
2       196054.98       882.89     198561.71       913.38    199581.38    957.33
3       194069.27       874.08     197837.62       910.07    199370.56    956.33
 
Week7.java.txt
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26128984
You had a minor mistake in your print statement. See Code for modification.
After answering No, you now get following output:
*****************************************************
* Loan Term       Interest Rate      Mortgage Payment    *
*****************************************************
7  Years      5.35%            $891,666.67
15  Years      5.5%            $916,666.67
30  Years      5.75%            $958,333.33

Your Mortgage Payment seems a little high.
// displays term in years, interest rates, and payments
System.out.println((iTerm[i]/12) + "  Years" + "\t"
       + ((dInterest[i])) + "%" + "\t\t"
       + f.format(payment));

Open in new window

0
 

Author Comment

by:coldjava
ID: 26129066
Phoffric --

Thanks so much. Yes, one of my problems has been with the Mortgage Payment being too high.

It should display with these numbers:

                          Mortgage Payment
                                $2859.79
                                $1634.17
                                $1167.15

How can I correct that?  

Thanks again.
 
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26129078
Show me the the correct formula for the calculation (include all units), and I will check it against your code.
0
 

Author Comment

by:coldjava
ID: 26129098
Phoffric

Thanks. The correct version should look like this:

Loan Term      Interest Rate        Mortgage Payment
7 years          5.35%                   $2859.79
15 years        5.5%                     $1634.17
30 years        5.75%                   $1167.15

Next, the user should enter 2000000 and Yes.
There should be only 7 columns displayed. Each column should display a number.
Column 1 -- Payment number
Column 2 -- the first loan balance
Column 3 -- the first loan interest paid
Column 4 -- the second loan balance
Column 5 -- the second loan interest paid
Column 6 -- the third loan balance
Column 7 -- the third loan interest paid

The display should appear like this:
1       198031.88       891.67     199282.50       916.67    199791.19    958.33
2       196054.98       882.89     198561.71       913.38    199581.38    957.33
3       194069.27       874.08     197837.62       910.07    199370.56    956.33
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26129140
1. For Yes, your header should show 7 fields; you only show 5:
     Term   Payment    Monthly Interest   Monthly Principle   Balance
These columns do not correspond to your 7 column descriptions.

2. For Yes, you say there should be 7 columns including the 2nd and 3rd loan interest paid.
But in your expected display, you show 3 rows starting with 1, 2, 3. Aren't these for the 1st, 2nd and 3rd payments? What do the 2nd and 3rd loan interest paid mean on, say, the 5th row?

3. For Yes, you say that you get all 0's. I ran your program, and I get:
1      1109076.39          743.06       601492.77          423.61       314020.54          240.18
2       174136.38          116.67        94440.54           66.51        49304.45           37.71
3        27341.20           18.32        14828.13           10.44         7741.30            5.92

4. For No, you repeated (from your original question) the expected results of the correct formula, not the formula itself. Would you like me to evaluate your code for payment against the formula to see if it correct? If so, please provide the formula, and I'll be able to do so. (Include all units.) Somehow, you chose an implementation for payment. How? Your implementation for payment is as follows:


payment = this.dAmount * 
	( (dInterest[i] / 12) /
	(1 - Math.pow(1 / (1 + (dInterest[i] / 12)) ,
	             (  (iTerm[i])* 12 )  ) ) );

Open in new window

0
 

Author Comment

by:coldjava
ID: 26129257
Phoffric --

Thanks for the help. I am attaching my latest code. The "no" portion works now. Still having problems with the "yes" portion.

I only show what my Classroom Syllabus instructions provides.

You are correct, I am getting numbers now instead of zeros. Yet, it is still running away with itself and the figures do not match the example provided in the Syllabus. Instead of 1, 2, 3, etc., it is starting in the 200s and going endlessly.

When you mention formula including all units, what exactly are you talking about? Thanks again.  
Week7.java
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26129292
The payment code is producing numbers to high, right? Where did you get this payment code? I was assuming that you coded it based upon some math equations that you were given. If you were not given such an equation, then how did you code the payment calculation?
0
 

Author Comment

by:coldjava
ID: 26129340
Phoffric --

Thanks for the reply. The first portion where 200000 is entered followed by a No entry is working correctly now.  

On the second portion where 200000 and Yes, is the only part not working properly.

On this Yes portion, someone on Expert Exchange gave me this code. When I tested the code the 7 columns were not displaying properly (lots of zeros and the columns were endless). I wrote them back but they never responded -- just dropped the communication.

Then someone else recommended a few changes and now numbers display after entering Yes but it is still not correct.

That is where I am now.

Is this a major coding problem?

What needs to be done? Thanks.
 

   

 
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26129490
1. re: "The first portion where 200000 is entered followed by a No entry is working correctly now."
In original question, you say to enter 2000000, not 200000. So, which answer corresponds to which input?

Enter: 2000000
*****************************************************
* Loan Term       Interest Rate      Mortgage Payment    *
*****************************************************
7  years      5.35%            $28,597.91
15  years      5.5%            $16,341.67
30  years      5.75%            $11,671.46

Enter: 200000
7  years      5.35%            $2,859.79
15  years      5.5%            $1,634.17
30  years      5.75%            $1,167.15

2. re: "someone on Expert Exchange gave me this code"
Please provide the link for review.

3. re: "someone else recommended a few changes"
Please provide the link for review.

4. For Yes, your header should show 7 fields; you only show 5:
     Term   Payment    Monthly Interest   Monthly Principle   Balance
Correct the printed headers to match your description or vice versa.

5. For Yes, you say there should be 7 columns including the 2nd and 3rd loan interest paid.
But in your expected display, you show 3 rows starting with 1, 2, 3. Aren't these for the 1st, 2nd and 3rd payments? What do the 2nd and 3rd loan interest paid mean on, say, the 5th row?
 -- If my understanding of the meaning of the 2nd and 3rd loan interest paid is correct, then are you sure your assignment requires 360 rows to be printed out? I do not understand the homework assignment as you have stated.
0
 

Author Comment

by:coldjava
ID: 26135373
Phoffric --

I heard back from my instructor. This is what he had to say about my current code:

It is 7 vertical columns. The first column is the payment number. The 30 years loan should have 2 columns of 360 sets values (360 rows). The 15 years loan should have 2 columns of 180 sets values (180 rows). And the 7 years loan should have 2 columns of 84 sets values (84 rows). The requirement description table puts the values in the order of the 30 years loan, 15 years loan and 7 years loan.

Also, he said: There are three things I need to fix:

1.      1. Not all three loans have 360 payments. The 15 years loan only has 180 payments and the 7 years loan only has 84 payments. Within their case, if the payment number is greater than the last payment number (180 or 84) set the interest and balance to zeros.

2.      2. The balance and interest amounts are not correct.

3. The program should not run 360 all the way to the end. It should pause after showing certain number of records.

I suggest fixed the first problem first before fixing the other two problems. After you have fixed the first problem, you can repost the program source code and I will step you through. The second problem takes a few more changes.The third problem require using two loops.

0
 

Author Comment

by:coldjava
ID: 26135403
Phoffric --

The assignment requires the writing of a program in Java (without a graphical user interface) and have it calculate the payment amount for 3 mortgage loans.

 7 years at 5.35%
15 years at 5.5%
30 years at 5.75%

Use an array for the different loans. Display the mortgage payment amount for each loan and then list the loan balance and interest paid for each payment over the term of the loan. Use loops to prevent lists from scrolling off the screen.    

From this information I hope you can help me to accurately complete the assignment. Thanks.

 
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26135601
A. For the "No" case, you said that the monthly payment was correct. So, computing the balance and interest amounts should be easy. Right? In http:#26129490 - item #1, I expressed some confusion about your input and output for the "No" case. Could you address this point so that I know what the correct input and output are.

B. Your clarification does help make your requirements clearer. Here is my understanding:
Column 1 -- Payment number
Column 2 -- the 30 years loan balance (360 rows)
Column 3 -- the 30 years loan interest paid (360 rows)
Column 4 -- the 15 years loan balance (180 rows)
Column 5 -- the 15 years loan interest paid (180 rows)
Column 6 -- the 7 years loan balance (84 rows)
Column 7 -- the 7 years loan interest paid (84 rows)

So, your first really easy step is to make a 7 column header. (I suggest making that a simple method to facilitate the "pause" after, say 12 records; i.e., 1 year.)

C. re: "2. The balance and interest amounts are not correct."
You provided the correct answers for the "No" scenario, so now provide the correct answer for the "Yes" scenario. (Otherwise, how will you know whether the program is giving the right answer?) Doing the entire 360 lines might be tiring; so just provide the first two lines. You'll know if the program is working if (1) you get the same first two lines that you know are correct, and if (2) after the 360 payments, the balance and interest are zero.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26135631
re: "Use an array for the different loans."
Yes, this is very good advice. Instead of dMonthlyInterest1,..., make an array dMonthlyInterestPaid[3]. Likewise, make an array for dBalanceDue and for dMonthlyPrinciplePaid (if you need this one).

Now that you have arrays for the important values, you can just compute the three types of loans in a loop without needing the three case statements for "switch (p)". Imagine what your code would look like if the requirement had 20 different loan cases. You'd have 20 case statements. With the array and loop that you will implement, the code stays the same except for the bounds of the for loop. Much easier this way.

If you are still getting wrong answers after doing these steps, please submit your code and I'll see if I can give you more guidance.
0
 

Author Comment

by:coldjava
ID: 26141930
Phoffric --

 My instructor provided additional input.

Here is what he said:
"Your Yes option on the assignment needs to show the amortization 7 columns. At present your code has 7 columns for 360 rows. However only the 30 years loan needs 360 rows. On the 7 year and 15 year loans there needs to be less rows."

How does this affect what I need to be working on based on the instructions you offered above?
Is it easy to have columns that are so lopsided?

Currently when I enter 200000 and Yes, prior code display disappears and the entire Command Prompt shows just the rows and long columns. Is this how it should look on the screen?

 
Thanks for the help.


0
 
LVL 32

Expert Comment

by:phoffric
ID: 26142185
re: "lopsided"
In earlier post you said "if the payment number is greater than the last payment number (180 or 84) set the interest and balance to zeros."
So, your program writes out 360 rows. But the 15 year columns will have 0's for the bottom half.

re: "I enter 200000 and Yes, prior code display disappears and the entire Command Prompt shows just the rows and long columns. Is this how it should look on the screen?"
What exactly disappears? Here is what I get for this scenario:
--
Please enter the loan amount as a number:
200000
Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:
Yes

Loan Amount = $200,000.00

*****************************************************
* Loan Term       Interest Rate      Mortgage Payment    *
*****************************************************
7  years      5.35%            $2,859.79
15  years      5.5%            $1,634.17
30  years      5.75%            $1,167.15

An 7-month loan equals a 0-year loan.          <<==== what are these 3 lines about?
An 15-month loan equals a 1-year loan.
An 30-month loan equals a 2-year loan.       <<==== makes no sense to me

Term   Payment    Monthly Interest   Monthly Principle   Balance
1       199973.41            0.74       199913.39            0.76       199786.15            0.80
2       199759.59            0.74       199699.63            0.76       199572.54            0.80
3 .....
....
360 ...
0
 

Author Comment

by:coldjava
ID: 26142626
Phoffric --

 Thanks for the reply. On my Command Prompt, I go through the standard entries such as cd C:\java, etc. and then java> dir.
This is followed by a display of the contents from my Java.
Then I enter javac -classpath ./  Week7.java
> java Week7
At this point I get into the entering the 200000 and No.
This leads to the display:

Loan Amount = $200,000.00

*****************************************************
* Loan Term       Interest Rate      Mortgage Payment    *
*****************************************************
7  years      5.35%            $2,859.79
15  years      5.5%            $1,634.17
30  years      5.75%            $1,167.15

Next I enter 200000 and Yes. When this happens all the other text displayed in the Command Prompt vanishes and all that remains is the long columns of numbers. There is no 1, 2, 3... It starts numbering in the 200s.

 I do not see on my Command Prompt I do not see the display below that you posted:

An 7-month loan equals a 0-year loan.          <<==== what are these 3 lines about?
An 15-month loan equals a 1-year loan.
An 30-month loan equals a 2-year loan.       <<==== makes no sense to me

Term   Payment    Monthly Interest   Monthly Principle   Balance
1       199973.41            0.74       199913.39            0.76       199786.15            0.80
2       199759.59            0.74       199699.63            0.76       199572.54            0.80
3 .....
....
360 ...    

Thanks.
Screen-Shot.doc
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26142866
Looks like you are overflowing your command prompt screen. See attached image for 3-steps to give you a scrollbar that will let you see the start of your output.

You can also do this:

> java Week7 > w7.txt
200000
Yes
 (NOTE: you will not see prompts, which are put into the txt file.)
Now you can look at the w7.txt file.
commandPrompt.JPG
0
 

Author Comment

by:coldjava
ID: 26142964
Phoffric --

Thanks so much.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26142990
Instead of building and running from a command prompt, why not download netbeans or eclipse to edit and build your java programs. I'm using eclipse which shows me errors as I type them.
0
 

Author Comment

by:coldjava
ID: 26146736
Phoffric --

 OK. Thanks for the suggestion.
0
 

Author Comment

by:coldjava
ID: 26151022
Phoffric --

Here is my code for creating arrays and loops for the Yes portion. I am only submitting the new code text.

Is it correct? According to the instructor only the 30 year loan needs to go to 360 rows. The other two loan years are not that long. There is supposed to be a pause in the display too. Thanks.

double [ ] payment = new double [3];
double []  sevenYearInterest = new  double [84];
double [ ] fifteenYearInterest = new double [180];
double [ ] thirtyYearInterest = new double[360];

//Loop to determine payments and balance at each monthly interval

            while (paymentNumber <= 84)
            {

                  newBalance = balance;                        //allows payment subtraction in succession

                  monthlyInterestPaid = newBalance * monthlyRate;

                  principlePayment = payment - monthlyInterestPaid;

                  balance = newBalance - principlePayment;

                  

                  //displays output

                  System.out.println(paymentNumber + "\t" + f.format (payment) + "\t" + f.format (newBalance) + "\t" + f.format (monthlyInterestPaid));            

                  
                  //increment payment number and count by 1      
                  
                  paymentNumber++;

                  count++;

                  
                  //cause program to pause

                  if (count == 25)

                  {

                        Thread.sleep (2000);

                        count = 0;

                  }      
            
                  
            }

            System.out.println ("Final payment reduces balance to $0.00");

      }

}

//Loop to determine payments and balance at each monthly interval

            while (paymentNumber <= 180)
            {

                  newBalance = balance;                        //allows payment subtraction in succession

                  monthlyInterestPaid = newBalance * monthlyRate;

                  principlePayment = payment - monthlyInterestPaid;

                  balance = newBalance - principlePayment;

                  //displays output

                  System.out.println(paymentNumber + "\t" + f.format (payment) + "\t" + f.format (newBalance) + "\t" + f.format (monthlyInterestPaid));            

                  
                  //increment payment number and count by 1      
                  
                  paymentNumber++;

                  count++;

                  //cause program to pause

                  if (count == 25)

                  {

                        Thread.sleep (2000);

                        count = 0;

                  }      
            
                  
            }

            System.out.println ("Final payment reduces balance to $0.00");

      }

}

//Loop to determine payments and balance at each monthly interval

            while (paymentNumber <= 360)
            {
                  newBalance = balance;                        //allows payment subtraction in succession

                  monthlyInterestPaid = newBalance * monthlyRate;

                  principlePayment = payment - monthlyInterestPaid;

                  balance = newBalance - principlePayment;
                  //displays output

                  System.out.println(paymentNumber + "\t" + f.format (payment) + "\t" + f.format (newBalance) + "\t" + f.format (monthlyInterestPaid));            
                  //increment payment number and count by 1      
                  paymentNumber++;
                  count++;

                  
                  //cause program to pause

                  if (count == 25)

                  {

                        Thread.sleep (2000);

                        count = 0;
                  
            System.out.println ("Final payment reduces balance to $0.00");

      }

}
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26151539
If you could submit your code in the "Code" section in the future, it would be nicer. It gives line numbers for us to talk about, and it consumes less space in the blog (and it often comes out color coded which makes it easier to read; and it allows a Select All option for copying the code).

 I would like to review my suggestion in http:#26135631where I wrote: "make an array dMonthlyInterestPaid[3]"; and  "you can just compute the three types of loans in a loop without needing the three case statements for "switch (p)". I did not mean that you would save all 84,... , or 360 values for each array; rather you compute for the three loans the needed values for one pay period. And then you print it out, saving whatever you need for the next pay period. If you went with this approach, then you would have:
   dMonthlyInterestPaid[0]  ~ 30 year loan
   dMonthlyInterestPaid[1]  ~ 15 year loan
   dMonthlyInterestPaid[2]  ~  7 year loan

You have taken a different approach, which is your decision. But in that case, please explain your new design plans. Your submitted code doesn't show all the changes necessary for your new definitions, so I'll wait for a complete submission of your entire program. For example, sevenYearInterest[84] is now defined; but I do not see any usage of sevenYearInterest so it is not clear how you are setting the values. But, presumably, your plan now is to compute all 84 values of sevenYearInterest from the first payment period to the last. But, now you need special blocks of code to handle the three different loans. Suppose that after you got your program working with your approach, the next assignment asked you to add on 3 extra loans for a total of 6 loans to print out. Of course you would have to have extra columns, but that is following the same pattern as the first three, so no big deal. But, where you have special code sections for each loan type, now you have to create additional code sections for the three new loans - and this is not good; it is considered very bad programming practice. Now, if I am missing the point of your new design, please let me know. If my guess is correct, then let me know how you would like to proceed.

With the approach I was talking about (i.e., several arrays of 3 elements), then the loops run from 0..2 to compute each item.

Now, here's a new question for you. Are you supposed to make a class, say, Loan; and then you define an array of three objects of this class to correspond to the three loans. This is the correct OO way that is used in Java programming. Now the loop is over the number of loans. If you do not understand what I'm talking about, then maybe this will be explained in a future assignment.

As you said in earlier post, deal with the pause as the last step in your program.

0
 

Author Comment

by:coldjava
ID: 26155650
Phoffric --
 Thanks for the reply. Basically I have problems keeping up with the advice. I do not do things to be arbitrary. From my messages to should be obvious I am struggling to work this out. I get some input from my teacher. I try to make sense of this information and to comprehend what is being told be me in Expert Exchange.
Right now the numbers in the columns that do display in the Yes portion do not match those in my classroom instruction. I do not understand why it is not calculating correctly when it correctly calculates and displays in the No portion. According to my intructor, only the 30 year loan figures should extend to 360 rows. The 7 year and 15 year loans should not.  
The instructor also stated that I need an array,  a loop for each array and pauses.
 The Columns number correctly now, starting with 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16...
 The rest is not working.  
This is the array provided by the instructor in one reply:
 double [ ] payment = new double [3];
 He also said to: Provide a loop for each and pause. Remember to use [ i ]
The 30 year loan will use 360 rows. The 7 year loan will use 84 rows and the 15 year loan will use 180 rows.
It is 7 vertical columns. The first column is the payment number. The 30 years laon should have 2 coulmns of 360 sets values (360 rows). The 15 years loan should have 2 columns of 180 sets values (180 rows). And the 7 years loan should have 2 columns of 84 sets values (84 rows). The requirement description table puts the values in the order of the 30 years loans, 15 years loan and 7 years loan.  

There should be only 7 columns displayed. Each column should display a number.
Column 1 -- Payment number
Column 2 -- the first loan balance
Column 3 -- the first loan interest paid
Column 4 -- the second loan balance
Column 5 -- the second loan interest paid
Column 6 -- the third loan balance
Column 7 -- the third loan interest paid

The display should appear like this:
1       198031.88       891.67     199282.50       916.67    199791.19    958.33
2       196054.98       882.89     198561.71       913.38    199581.38    957.33
3       194069.27       874.08     197837.62       910.07    199370.56    956.33

 Thanks again.    
Week07.java
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26156518
Your attachment Week07.java says "(Possible File Type Mismatch)   Altered Code"
Try putting your code in the Code box rather than using the File attachment box.
After the monthlyBalance() method ends, there is missing code. The next line should be the start of another method, but it is just a println() statement within a missing method.
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26161924
Hello coldjava,

I am trying to understand what you are asking for, but I am not sure.

I have looked at the latest .java you attached and I am not even able to compile it.

I have now written a little code just for the calculation and print report part. You should be able to compile it and see if the output is correct, if so, you may see the correct algorithm/calculation in my code.
public class Week07
{
	public static void main(String[] args)
	{
    	// Declaration and initializing
	   	double loan = 200000;
	    int [] term = {7, 15, 30};                                                
    	double [] interestRate = {5.35, 5.5, 5.75};
    	double [] balance  = new double[term.length];
    	double [] interestPaid	 = new double[term.length];
    	double [] mortagePayment = new double[term.length]; 

		// Print header for term information
		System.out.printf("%-11s%s%18s","Loan Term", "Interest Rate", "Mortage Payment\n");
		
		// Fill balance array
		for (int i = 0; i <= balance.length -1; i++)
			balance[i] = loan;
		
		// Calculate and print mortagePayment array
		for (int i = 0; i <= term.length -1; i++)
		{
			mortagePayment[i] = ((interestRate[i]/1200)/(1- Math.pow((1+interestRate[i]/1200),(-term[i]*12))))*loan;
			System.out.printf("%2s%13.2f%%%11s%.2f\n"	, term[i], interestRate[i], "$", mortagePayment[i]);
			
			if (i == term.length-1)
				System.out.println();
		}
	
		// Display report
		for (int i = 1;; i++)
		{
			System.out.printf("%-5d", i);
			for (int j = 0; j <= interestPaid.length -1; j++)
			{
				interestPaid[j] = (balance[j] * (interestRate[j]/100 + 1) - balance[j]) / 12 ;
				balance[j] = balance[j] + interestPaid[j] - mortagePayment[j];
				
				if (interestPaid[j] > 0)
					System.out.printf("%-11.2f%-11.2f", (balance[j]), interestPaid[j]);

				else
					System.out.printf("%-11s%-11s", "", "");
			}
			
			System.out.println();
			if (balance[balance.length-1] <= 0) break;
		}
	}
}

Open in new window

0
 

Author Comment

by:coldjava
ID: 26162160
Nordtorp --

 Thanks for the reply and assistance. I will send another version of my code. My assignment is in two portions. On the first portion, a simple table displays after entering an amount and a "No" option.  

Enter an amount:
200000
Enter a Yes or No:
No  

The correct version should look like this:

Loan Term      Interest Rate        Mortgage Payment
7 years          5.35%                   $2859.79
15 years        5.5%                     $1634.17
30 years        5.75%                   $1167.15

That portion works.

The second portion of my assignment is more difficult. I still enter an amount: 200000 and a "Yes" option.

Enter an amount:
200000
Enter Yes or No
Yes

There should be only 7 columns displayed. Each column should display a number.
Column 1 -- Payment number
Column 2 -- the first loan balance
Column 3 -- the first loan interest paid
Column 4 -- the second loan balance
Column 5 -- the second loan interest paid
Column 6 -- the third loan balance
Column 7 -- the third loan interest paid

The display should appear like this:
1       198031.88       891.67     199282.50       916.67    199791.19    958.33
2       196054.98       882.89     198561.71       913.38    199581.38    957.33
3       194069.27       874.08     197837.62       910.07    199370.56    956.33

There are supposed to be more rows than the third shown about but these are examples of how it should look.
The first column is the payment numbers. For the 30 year loan there will be 360 payments but the display should not go all the way to the bottom with 360 rows. There should be a pause after a certain number of records. The 15 year loan has 180 payments and the 7 year loan only has 84 payments.
Within  their case if the payment number is greater than the last payment number (180 or 84) set the interest and balance to zeros.
According to my instructor the program should not run 360 all  the way to the end. It should pause after showing a certain number of records.

Thanks again.  
/**
 Programming 420 WilliamsWeek4 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class WilliamsWeek4  {

	// Declaring and constructing variables
	private int[] iTerm = { 84, 180, 360 };
	private double[] dInterest = { 5.35, 5.5, 5.75 };
	private double dPayment, dRate, dAmount = 200000, dMonthlyInterest1,
			dMonthlyInterest2, dMonthlyInterest3, dMonthlyPrinciple,
			dMonthlyBalance1, dMonthlyBalance2, dMonthlyBalance3;

	DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

	private boolean showReport = false;

	/**
	 * Default constructor
	 */
	public WilliamsWeek4() {
	}

	/**
	 * The main function for the mortgage calculator
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// Create an object of WilliamsWeek4 to process the Mortgage
		WilliamsWeek4 mortgageCalculator = new WilliamsWeek4();
		mortgageCalculator.acceptInput();
		mortgageCalculator.process();
	}

	/**
	 * Function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @return
	 */
	private double MonthlyInterest(double amount, double interestRate) {
		// Declaring Variables for interest on the loan
		double dMonthlyInterest = 0.0;
		// Calculation for monthly interest
		dMonthlyInterest = (amount / 12) * (interestRate / 100);
		return dMonthlyInterest;
	}

	/**
	 * function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @param term
	 * @return
	 */
	private double monthlyPayment(double amount, double interestRate,
			double term) {
		// Declaring Variables for interest on the loan
		double dMonthlyPayment = 0.0;
		// Calculation for monthly interest
		dMonthlyPayment = (amount * interestRate)
				* (1 - Math.pow(1 / (1 + interestRate), term));
		if (amount <= 0 || dMonthlyPayment <= 0) {
			dMonthlyPayment = 0.0;
		}
		return dMonthlyPayment;
	}

	/**
	 * function for the calculation of the monthly loan balance
	 * 
	 * @param amount
	 * @param monthlyPayment
	 * @return
	 */
	private double monthlyBalance(double amount, double monthlyPayment) {
		// Declaring Variables for monthly loan balance
		double dMonthlyBalance = 0.0;
		// Calculations for monthly loan balance
		dMonthlyBalance = (amount - monthlyPayment);
		if (dMonthlyBalance <= 0) {
			dMonthlyBalance = 0.0;
		}
		return dMonthlyBalance;
	}

	/**
	 * Function to show the Mortagage Schedule
	 */
	private void showMortagageSchedule() {
		// output for month to years
		for (int i : iTerm)
			System.out.println(String.format(
					"An %1$s-month loan equals a %2$s-year loan.", i, i / 12));

		System.out.println();
		System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
				"Term", "Payment", "Monthly Interest", "Monthly Principle",
				"Balance"));
		// Loop for the varying Mortgage Rates and Payments

		// Month counter
		for (int i = 1; i <= 360; i++) {
			for (int p = 0; p <= 2; p++) {
				// Calculation for the monthly mortgage payment
				dRate = dInterest[p] / 1200;
				switch (p) {
				case 0:
					dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
							iTerm[p]);
					dMonthlyInterest1 = MonthlyInterest(dAmount,
							dInterest[p] / 12);
					dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
					dMonthlyBalance1 = monthlyBalance(dAmount,
							dMonthlyPrinciple);
					dAmount = dMonthlyBalance1;
					break;
				case 1:
					dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
							iTerm[p]);
					dMonthlyInterest2 = MonthlyInterest(dAmount,
							dInterest[p] / 12);
					dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
					dMonthlyBalance2 = monthlyBalance(dAmount,
							dMonthlyPrinciple);
					dAmount = dMonthlyBalance2;
					break;
				case 2:
					dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
							iTerm[p]);
					dMonthlyInterest3 = MonthlyInterest(dAmount,
							dInterest[p] / 12);
					dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
					dMonthlyBalance3 = monthlyBalance(dAmount,
							dMonthlyPrinciple);
					dAmount = dMonthlyBalance3;
					break;
				}

			}
			// Output for the loan information and the monthly payment
			// System.out.println("Your Monthly Payment for a " + iTerm[p] +
			// " month loan of $200,000 at " + dInterest[p] + "% is:" +
			// twoDigits.format(dPayment));
			System.out
					.println(String
							.format(
									"%1$s\t%2$10.2f\t%3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f",
									i, dMonthlyBalance1, dMonthlyInterest1,
									dMonthlyBalance2, dMonthlyInterest2,
									dMonthlyBalance3, dMonthlyInterest3));
		}
	}

	/**
	 * Function to accept input from user and set it to class level variables
	 */
	public void acceptInput() {

		double principle = 0;
		// begins loop for input error checking
		boolean goodNumber = false; // declares goodNumber as boolean
		String userChoice = "No";

		// open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		// while loop lets try and catch statements determine if an exception
		// requires user to reinput
		while (!goodNumber) {
			// try statement in case of exception such as user entering a string
			try {
				// informs user to enter amount of desired loan
				System.out
						.println("Please enter the loan amount as a number: ");
				// delcares Scanner object
				Scanner input = new Scanner(br);
				principle = input.nextDouble();
				if (principle <= 0.0) {
					System.out
							.println("Error:  Loan Amount must be greater than $0.00");
					continue; // This causes the loop to continue without
					// executing statements after this code
				}
				// Set the local variable to the class level variable
				this.dAmount = principle;
				// set goodNumber to true if no exception to let program
				// continue
				goodNumber = true;
			} catch (Exception e) {
				System.out
						.println("Error: The entered number is invalid or not a number. Please enter a valid number.");
			}
		}

		System.out
				.println("Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:");
		try {
			userChoice = br.readLine();
			if (userChoice == null || "".equals(userChoice.trim())) {
				System.out
						.println("No input provided. By default the report will not be shown ");
			} else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
					.equalsIgnoreCase(userChoice))) {
				System.out
						.println("Invalid input provided. By default the report will not be shown ");
			} else if ("Yes".equalsIgnoreCase(userChoice)) {
				showReport = true;
			}
			// The else condition of userChoice="No" is already covered with
			// intitialization
		} catch (IOException ioe) {
			System.out.println("IOException while reading input: "
					+ ioe.getMessage());
		}
	}

	/**
	 * Function to process the output
	 */
	public void process() {

		DecimalFormat f = new DecimalFormat("$###,###.00");
		double payment;

		// if statement to ensure user enters amount greater than 0
		if (this.dAmount > 0)

		{
			// informs user of desired loan amount
			System.out.println("\nLoan Amount = " + f.format(this.dAmount));

			// displays calculator headings
			System.out
					.println("\n\n*****************************************************");
			System.out.println("* Loan Term " + "\tInterest Rate"
					+ "\tMortgage Payment    *");
			System.out
					.println("*****************************************************");
			// begins loop to determine terms, rates, and payments
			for (int i = 0; i < dInterest.length; i++) {
				// calculations to determine payment
				payment = this.dAmount
						* ((dInterest[i] / 12) / (1 - Math.pow(
								1 / (1 + (dInterest[i] / 12)),
								((iTerm[i]) * 12))));
				// displays term in years, interest rates, and payments
				System.out.println((dInterest[i]) + "  years" + "\t"
						+ ((dInterest[i]) * 100) + "%" + "\t\t"
						+ f.format(payment));

			}

			System.out.println();

			if (this.showReport) {
				// Call function to show the mortgage schedule
				showMortagageSchedule();
			}
		}
	}
}

Open in new window

0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26162372
First of all, when I run your last code and enter no, I get this:

*****************************************************
* Loan Term       Interest Rate      Mortgage Payment    *
*****************************************************
5.35  years      535.0%            $89 166,67
5.5  years      550.0%            $91 666,67
5.75  years      575.0%            $95 833,33

Something is entered incorrectly here. Check what you are printing.
1. Loan term should be 7, 15 and 30. Not 5.35, 5.5 and 5.75
2. Interest rate should be 5.35, 5.5 and 5.75. Not the 535% and so on.
3. Mortage Payment is way too large.

Could you start to tell us what formula you have used to calculate Mortage Payment?
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26162398
One more thing, in order to solve portion two, you have to get portion one correct, you have to use mortgage payment to calculate loan balances after payment.

As in:

new balance = old balance + rate - payment.
 X  = 200000 + 891.67 - 2859.79 = 198031.88
0
 

Author Comment

by:coldjava
ID: 26162840
Nordtorp --

Thanks. I am sending a different version of my code.  Every time I attempt to make changes it effects the No portion. This is probably one of the versions I attached for you in the other post. Sorry about that.
                   
When I used this latest version the "No" table displays the correct numbers.

Loan Term      Interest Rate        Mortgage Payment
7 years          5.35%                   $2859.79
15 years        5.5%                     $1634.17
30 years        5.75%                   $1167.15

According to my instructor this portion is correct.

However, the second portion where Yes is entered is where it messes up. Such as it displays the first No portion table again and three lines of unneeded code.

The headings are not correct on the Yes portion either.

On the Yes portion I think I need to have code that does this:

private int[] iMonth = {84, 180, 360};

Then within each case statement, use a if-then-else:

1. Declare the number of months at the beginning of the main code using
        private int[] iMonth = {84, 180, 360};
2. Within each case statement, use a if-then-else

case 0:  // 7 year loan
                    if (i <= iMonth[p]) {
                    dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
                            iTerm[p]);
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                            dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

After the fix, the zeros after the loan expires are fine, but my values are still not correct.

Thanks again.
 
/**
 Programming 420 WilliamsWeek4 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class WilliamsWeek4 {

	// Declaring and constructing variables
	private int[] iTerm = {7, 15, 30};
	private double[] dInterest = {.0535, .055, .0575};
	private double dPayment, dRate, dAmount = 200000, dMonthlyInterest1,
			dMonthlyInterest2, dMonthlyInterest3, dMonthlyPrinciple,
			dMonthlyBalance1, dMonthlyBalance2, dMonthlyBalance3;

	DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

	private boolean showReport = false;

	/**
	 * Default constructor
	 */
	public WilliamsWeek4() {
	}

	/**
	 * The main function for the mortgage calculator
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// Create an object of WilliamsWeek4 to process the Mortgage
		WilliamsWeek4 mortgageCalculator = new WilliamsWeek4();
		mortgageCalculator.acceptInput();
		mortgageCalculator.process();
	}

	/**
	 * Function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @return
	 */
	private double MonthlyInterest(double amount, double interestRate) {
		// Declaring Variables for interest on the loan
		double dMonthlyInterest = 0.0;
		// Calculation for monthly interest
		dMonthlyInterest = (amount / 12) * (interestRate / 100);
		return dMonthlyInterest;
	}

	/**
	 * function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @param term
	 * @return
	 */
	private double monthlyPayment(double amount, double interestRate,
			double term) {
		// Declaring Variables for interest on the loan
		double dMonthlyPayment = 0.0;
		// Calculation for monthly interest
		dMonthlyPayment = (amount * interestRate)
				* (1 - Math.pow(1 / (1 + interestRate), term));
		if (amount <= 0 || dMonthlyPayment <= 0) {
			dMonthlyPayment = 0.0;
		}
		return dMonthlyPayment;
	}

	/**
	 * function for the calculation of the monthy loan balance
	 * 
	 * @param amount
	 * @param monthlyPayment
	 * @return
	 */
	private double monthlyBalance(double amount, double monthlyPayment) {
		// Declaring Variables for monthly loan balance
		double dMonthlyBalance = 0.0;
		// Calculations for monthly loan balance
		dMonthlyBalance = (amount - monthlyPayment);
		if (dMonthlyBalance <= 0) {
			dMonthlyBalance = 0.0;
		}
		return dMonthlyBalance;
	}

	/**
	 * Function to show the Mortagage Schedule
	 */
	private void showMortagageSchedule() {
		// output for month to years
		for (int i : iTerm)
			System.out.println(String.format(
					"An %1$s-month loan equals a %2$s-year loan.", i, i / 12));

		System.out.println();
		System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
				"Term", "Payment", "Monthly Interest", "Monthly Principle",
				"Balance"));
		// Loop for the varying Mortgage Rates and Payments

		// Month counter
		for (int i = 1; i <= 360; i++) {
			for (int p = 0; p <= 2; p++) {
				// Calculation for the monthly mortgage payment
				dRate = dInterest[p] / 1200;
				switch (p) {
				case 0:
					dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
							iTerm[p]);
					dMonthlyInterest1 = MonthlyInterest(dAmount,
							dInterest[p] / 12);
					dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
					dMonthlyBalance1 = monthlyBalance(dAmount,
							dMonthlyPrinciple);
					dAmount = dMonthlyBalance1;
					break;
				case 1:
					dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
							iTerm[p]);
					dMonthlyInterest2 = MonthlyInterest(dAmount,
							dInterest[p] / 12);
					dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
					dMonthlyBalance2 = monthlyBalance(dAmount,
							dMonthlyPrinciple);
					dAmount = dMonthlyBalance2;
					break;
				case 2:
					dPayment = monthlyPayment(dAmount, dInterest[p] / 12,
							iTerm[p]);
					dMonthlyInterest3 = MonthlyInterest(dAmount,
							dInterest[p] / 12);
					dMonthlyPrinciple = (dPayment - dMonthlyInterest1);
					dMonthlyBalance3 = monthlyBalance(dAmount,
							dMonthlyPrinciple);
					dAmount = dMonthlyBalance3;
					break;
				}

			}
			// Output for the loan information and the monthly payment
			// System.out.println("Your Monthly Payment for a " + iTerm[p] +
			// " month loan of $200,000 at " + dInterest[p] + "% is:" +
			// twoDigits.format(dPayment));
			System.out.println(String.format("%1$s\t%2$10.2f\t%3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f", i, dMonthlyBalance1, 

dMonthlyInterest1, dMonthlyBalance2, dMonthlyInterest2, dMonthlyBalance3, dMonthlyInterest3));
		}
	}

	/**
	 * Function to accept input from user and set it to class level variables
	 */
	public void acceptInput() {

		double principle = 0;
		// begins loop for input error checking
		boolean goodNumber = false; // declares goodNumber as boolean
		String userChoice = "No";

		// open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		// while loop lets try and catch statements determine if an exception
		// requires user to reinput
		while (!goodNumber) {
			// try statement in case of exception such as user entering a string
			try {
				// informs user to enter amount of desired loan
				System.out
						.println("Please enter the loan amount as a number: ");
				// delcares Scanner object
				Scanner input = new Scanner(br);
				principle = input.nextDouble();
				if (principle <= 0.0) {
					System.out
							.println("Error:  Loan Amount must be greater than $0.00");
					continue; // This causes the loop to continue without
					// executing statements after this code
				}
				// Set the local variable to the class level variable
				this.dAmount = principle;
				// set goodNumber to true if no exception to let program
				// continue
				goodNumber = true;
			} catch (Exception e) {
				System.out
						.println("Error: The entered number is invalid or not a number. Please enter a valid number.");
			}
		}

		System.out
				.println("Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:");
		try {
			userChoice = br.readLine();
			if (userChoice == null || "".equals(userChoice.trim())) {
				System.out
						.println("No input provided. By default the report will not be shown ");
			} else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
					.equalsIgnoreCase(userChoice))) {
				System.out
						.println("Invalid input provided. By default the report will not be shown ");
			} else if ("Yes".equalsIgnoreCase(userChoice)) {
				showReport = true;
			}
			// The else condition of userChoice="No" is already covered with
			// intitialization
		} catch (IOException ioe) {
			System.out.println("IOException while reading input: "
					+ ioe.getMessage());
		}
	}

	/**
	 * Function to process the output
	 */
	public void process() {
		DecimalFormat f = new DecimalFormat("$###,###.00");
		double payment;

		// if statement to ensure user enters amount greater than 0
		if (this.dAmount > 0)

		{
			// informs user of desired loan amount
			System.out.println("\nLoan Amount = " + f.format(this.dAmount));

			// displays calculator headings
			System.out
					.println("\n\n*****************************************************");
			System.out.println("* Loan Term " + "\tInterest Rate"
					+ "\tMortgage Payment    *");
			System.out
					.println("*****************************************************");
			// begins loop to determine terms, rates, and payments
			char c = 160;
			for (int i = 0; i < dInterest.length; i++) {
				// calculations to determine payment
				payment = this.dAmount
						* ((dInterest[i] / 12) / (1 - Math.pow(
								1 / (1 + (dInterest[i] / 12)),
								((iTerm[i]) * 12))));
				// displays term in years, interest rates, and payments
				System.out.println((iTerm[i]) + "  years" + "\t" + ((dInterest[i]) * 100) + "%" + "\t\t" + f.format(payment).replaceAll

(""+c,","));
			}

			System.out.println();

			if (this.showReport) {
				// Call function to show the mortgage schedule
				showMortagageSchedule();
			}
		}
	}
}

Open in new window

0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26162893
First take a look at your monthly interest, you get those numbers to be like 0.74 and so on. This should be 800-900 to start with.

Try figuring out why monthly interest is incorrect before you do anything else.

Try to just write a little (new) program to calculate monthly interest and see if you get the correct numbers.

I will be here in case you have questions.
0
 

Author Comment

by:coldjava
ID: 26163522
Nordtorp --

Thanks. Also, I was wondering if the decimals are in the correct location?

private double[] dInterest = {.0535, .055, .0575};
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26163715
re: private double[] dInterest = {.0535, .055, .0575};

You are expressing the interest rate in fractional form rather than percentage form, and this is fine. You just have to be consistent throughout the usage of this item. Since you are using this item in your No calculation, and you say that the No results are correct, then the above line must also be correct.

Since you compute payment in the No case, you could make payment a class member, and then use it for the Yes scenario. This works since your Yes scenario includes the No scenario.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26163732
To do this you would need a member of the form:
private double monthlyPayment[3];

Then you fill in this monthlyPayment[i], for i=0..2 when you are computing the No scenario.

Now you can use this.

interest = current balance[i] * monthly interest rate[i]
balance = old balance[i] - monthlyPayment[i]
0
 

Author Comment

by:coldjava
ID: 26163789
Phoffric --

Thanks for the advice.

 
0
 

Author Comment

by:coldjava
ID: 26166541
Phoffric --

 My instructor has provided some step by step directions. He told me to insert private int [] iMonth = {84, 180, 360}; after the iTerm at the top.

Her also provided this code and told me to insert it in my code.

There are a few errors now. Unfortunately, while I followed my instructor's directions on what to do to make my code compile properly, he chewed me out for altering my code.

Also, he told me he was not going to be available until very late tonight. The assignment is due Monday. Apparently he washed his hands of me.

Anyway, you know what is required of my assignment. Can you direct me on exactly what I need to do to get the assignment using my instructor's code instructions. I would consider it a major victory over his walking off the job.

Thanks.        
/**
 Programming 420 Week33 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Week33 {

	// Declaring and constructing variables
	private int[] iTerm = {7, 15, 30};
	private double[] dInterest = {.0535, .055, .0575};
	private double dRate, dAmount, dMonthlyInterest1,
			dMonthlyInterest2, dMonthlyInterest3, dMonthlyPrinciple,
       			dMonthlyBalance1, dMonthlyBalance2, dMonthlyBalance3;
        private double[] dPayment = new double[3];
	DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

	private boolean showReport = false;

	/**
	 * Default constructor
	 */
	public Week33() {
	}

	/**
	 * The main function for the mortgage calculator
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// Create an object of Week33 to process the Mortgage
		Week33 mortgageCalculator = new Week33();
		mortgageCalculator.acceptInput();
		mortgageCalculator.process();
	}

	/**
	 * Function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @return
	 */
	private double MonthlyInterest(double amount, double interestRate) {
		// Declaring Variables for interest on the loan
		double dMonthlyInterest = 0.0;
		// Calculation for monthly interest
		dMonthlyInterest = (amount / 12) * (interestRate / 100);
		return dMonthlyInterest;
	}

	/**
	 * function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @param term
	 * @return
	 */
	private double monthlyPayment(double amount, double interestRate,
			double term) {
		// Declaring Variables for interest on the loan
		double dMonthlyPayment = 0.0;
		// Calculation for monthly interest
		dMonthlyPayment = (amount * interestRate)
				* (1 - Math.pow(1 / (1 + interestRate), term));
		if (amount <= 0 || dMonthlyPayment <= 0) {
			dMonthlyPayment = 0.0;
		}
		return dMonthlyPayment;
	}

	/**
	 * function for the calculation of the monthy loan balance
	 * 
	 * @param amount
	 * @param monthlyPayment
	 * @return
	 */
	private double monthlyBalance(double amount, double monthlyPayment) {
		// Declaring Variables for monthly loan balance
		double dMonthlyBalance = 0.0;
		// Calculations for monthly loan balance
		dMonthlyBalance = (amount - monthlyPayment);
		if (dMonthlyBalance <= 0) {
			dMonthlyBalance = 0.0;
		}
		return dMonthlyBalance;
	}

	/**
	 * Function to show the Mortagage Schedule
	 */
	private void showMortagageSchedule() {
		// output for month to years
		for (int i : iTerm)
        private int[] iMonth = {84, 180, 360}; 
                
			System.out.println(String.format(
					"An %1$s-month loan equals a %2$s-year loan.", i, i / 12));

		System.out.println();
		System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
				"Term", "Payment", "Monthly Interest", "Monthly Principle",
				"Balance"));
		// Loop for the varying Mortgage Rates and Payments

		// Month counter
		for (int i = 1; i <= 360; i++) {
			for (int p = 0; p <= 2; p++) {
				// Calculation for the monthly mortgage payment
				dRate = dInterest[p] / 1200;
				switch (p) {
				case 0:  // 7 year loan
                    if (i <= iMonth[p]) {
                    dPayment = payment;
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                            dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;


       case 0:  // 7 year loan
                    if (i <= iMonth[p]) {
                    dPayment = payment;
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                            dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;


          case 1:  // 15 year loan
                    if (i <= iMonth[p]) {
                    dPayment - payment; 
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

       
        case 2:  // 30 year loan
                    if (i <= iMonth[p]) {
                    dPayment = payment;
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

				}

			}
			// Output for the loan information and the monthly payment
			// System.out.println("Your Monthly Payment for a " + iTerm[p] +
			// " month loan of $200,000 at " + dInterest[p] + "% is:" +
			// twoDigits.format(dPayment));
			System.out.println(String.format("%1$s\t%2$10.2f\t%3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f", i, dMonthlyBalance1, 

dMonthlyInterest1, dMonthlyBalance2, dMonthlyInterest2, dMonthlyBalance3, dMonthlyInterest3));
		}
	}

	/**
	 * Function to accept input from user and set it to class level variables
	 */
	public void acceptInput() {

		double principle = 0;
		// begins loop for input error checking
		boolean goodNumber = false; // declares goodNumber as boolean
		String userChoice = "No";

		// open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		// while loop lets try and catch statements determine if an exception
		// requires user to reinput
		while (!goodNumber) {
			// try statement in case of exception such as user entering a string
			try {
				// informs user to enter amount of desired loan
				System.out
						.println("Please enter the loan amount as a number: ");
				// delcares Scanner object
				Scanner input = new Scanner(br);
				principle = input.nextDouble();
				if (principle <= 0.0) {
					System.out
							.println("Error:  Loan Amount must be greater than $0.00");
					continue; // This causes the loop to continue without
					// executing statements after this code
				}
				// Set the local variable to the class level variable
				this.dAmount = principle;
				// set goodNumber to true if no exception to let program
				// continue
				goodNumber = true;
			} catch (Exception e) {
				System.out
						.println("Error: The entered number is invalid or not a number. Please enter a valid number.");
			}
		}

		System.out
				.println("Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:");
		try {
			userChoice = br.readLine();
			if (userChoice == null || "".equals(userChoice.trim())) {
				System.out
						.println("No input provided. By default the report will not be shown ");
			} else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
					.equalsIgnoreCase(userChoice))) {
				System.out
						.println("Invalid input provided. By default the report will not be shown ");
			} else if ("Yes".equalsIgnoreCase(userChoice)) {
				showReport = true;
			}
			// The else condition of userChoice="No" is already covered with
			// intitialization
		} catch (IOException ioe) {
			System.out.println("IOException while reading input: "
					+ ioe.getMessage());
		}
	}

	/**
	 * Function to process the output
	 */
	public void process() {
		DecimalFormat f = new DecimalFormat("$###,###.00");
		double payment;

		// if statement to ensure user enters amount greater than 0
		if (this.dAmount > 0)

		{
			// informs user of desired loan amount
			System.out.println("\nLoan Amount = " + f.format(this.dAmount));

			// displays calculator headings
			System.out
					.println("\n\n*****************************************************");
			System.out.println("* Loan Term " + "\tInterest Rate"
					+ "\tMortgage Payment    *");
			System.out
					.println("*****************************************************");
			// begins loop to determine terms, rates, and payments
			char c = 160;
			for (int i = 0; i < dInterest.length; i++) {
				// calculations to determine payment
				payment = this.dAmount
						* ((dInterest[i] / 12) / (1 - Math.pow(
								1 / (1 + (dInterest[i] / 12)),
								((iTerm[i]) * 12))));
				// displays term in years, interest rates, and payments
				System.out.println((iTerm[i]) + "  years" + "\t" + ((dInterest[i]) * 100) + "%" + "\t\t" + f.format(payment).replaceAll

(""+c,","));
			}

			System.out.println();

			if (this.showReport) {
				// Call function to show the mortgage schedule
				showMortagageSchedule();
                 


			}
		}
	}
}

Open in new window

0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26166740
Here is what I have found out from your code that is incorrect:

- Two instances of case 0 - Remove one of them
- Your for-loop does not have any starting and ending brackets ({ and }) - Insert them were you want them to be
- your instructor asked you to move private int[] iMonth = {84, 180, 360}; to under iTerm, in that case, do that.
As in:
      private int[] iTerm = {7, 15, 30};
      private int[] iMonth = {84, 180, 360};
- There are also some problems with "payment" in line 123, 140 and 157.

As this is a homework and/or school project the guide lines at EE says we should not give you the answer, but rather help you to find the answer. So if you have a question, please ask one at the time as we cannot guess what is wrong from time to time. What are you struggling with after you have fixed the problems I have pointed out?
0
 

Author Comment

by:coldjava
ID: 26166896
Nordtorp --

Thank you very much. I am not sure what you mean about the payment.

 I have made the changes you suggested.

 I still lack adding the declaration dPayment as an array  

   private double[] dPayment = new double[3];

 Also, inside the process method, I need to assign payment to the dPayment array elements:

 dPayment = payment;

 I do not know where these should be placed. Should these also be placed at the beginning of the code? Is there anything else that needs to be corrected?

I know you are limited in how much you can tell me but I do appreciate the assistance you have provided. Thanks again.  


/**
 Programming 420 Week133 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Week133 {

	// Declaring and constructing variables
	private int[] iTerm = {7, 15, 30};
        private int[] iMonth = {84, 180, 360}; 
	private double[] dInterest = {.0535, .055, .0575};
	private double dRate, dAmount, dMonthlyInterest1,
			dMonthlyInterest2, dMonthlyInterest3, dMonthlyPrinciple,
       			dMonthlyBalance1, dMonthlyBalance2, dMonthlyBalance3;
        private double[] dPayment = new double[3];
	DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

	private boolean showReport = false;

	/**
	 * Default constructor
	 */
	public Week133() {
	}

	/**
	 * The main function for the mortgage calculator
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// Create an object of Week133 to process the Mortgage
		Week133 mortgageCalculator = new Week133();
		mortgageCalculator.acceptInput();
		mortgageCalculator.process();
	}

	/**
	 * Function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @return
	 */
	private double MonthlyInterest(double amount, double interestRate) {
		// Declaring Variables for interest on the loan
		double dMonthlyInterest = 0.0;
		// Calculation for monthly interest
		dMonthlyInterest = (amount / 12) * (interestRate / 100);
		return dMonthlyInterest;
	}

	/**
	 * function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @param term
	 * @return
	 */
	private double monthlyPayment(double amount, double interestRate,
			double term) {
		// Declaring Variables for interest on the loan
		double dMonthlyPayment = 0.0;
		// Calculation for monthly interest
		dMonthlyPayment = (amount * interestRate)
				* (1 - Math.pow(1 / (1 + interestRate), term));
		if (amount <= 0 || dMonthlyPayment <= 0) {
			dMonthlyPayment = 0.0;
		}
		return dMonthlyPayment;
	}

	/**
	 * function for the calculation of the monthy loan balance
	 * 
	 * @param amount
	 * @param monthlyPayment
	 * @return
	 */
	private double monthlyBalance(double amount, double monthlyPayment) {
		// Declaring Variables for monthly loan balance
		double dMonthlyBalance = 0.0;
		// Calculations for monthly loan balance
		dMonthlyBalance = (amount - monthlyPayment);
		if (dMonthlyBalance <= 0) {
			dMonthlyBalance = 0.0;
		}
		return dMonthlyBalance;
	}

	/**
	 * Function to show the Mortagage Schedule
	 */
	private void showMortagageSchedule() {
		// output for month to years
		for (int i : iTerm)
        private int[] iMonth = {84, 180, 360}; 
                
			System.out.println(String.format(
					"An %1$s-month loan equals a %2$s-year loan.", i, i / 12));

		System.out.println();
		System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
				"Term", "Payment", "Monthly Interest", "Monthly Principle",
				"Balance"));
		// Loop for the varying Mortgage Rates and Payments

		// Month counter
		for (int i = 1; i <= 360; i++) {
			for (int p = 0; p <= 2; p++) {
				// Calculation for the monthly mortgage payment
				dRate = dInterest[p] / 1200;
				switch (p) {
				

       case 0:  // 7 year loan
                    if (i <= iMonth[p]) {
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                            dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;


          case 1:  // 15 year loan
                    if (i <= iMonth[p]) {
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

       
        case 2:  // 30 year loan
                    if (i <= iMonth[p]) {
                                        dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

				}

			}
			// Output for the loan information and the monthly payment
			// System.out.println("Your Monthly Payment for a " + iTerm[p] +
			// " month loan of $200,000 at " + dInterest[p] + "% is:" +
			// twoDigits.format(dPayment));
			System.out.println(String.format("%1$s\t%2$10.2f\t%3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f", i, dMonthlyBalance1, 

dMonthlyInterest1, dMonthlyBalance2, dMonthlyInterest2, dMonthlyBalance3, dMonthlyInterest3));
		}
	}

	/**
	 * Function to accept input from user and set it to class level variables
	 */
	public void acceptInput() {

		double principle = 0;
		// begins loop for input error checking
		boolean goodNumber = false; // declares goodNumber as boolean
		String userChoice = "No";

		// open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		// while loop lets try and catch statements determine if an exception
		// requires user to reinput
		while (!goodNumber) {
			// try statement in case of exception such as user entering a string
			try {
				// informs user to enter amount of desired loan
				System.out
						.println("Please enter the loan amount as a number: ");
				// delcares Scanner object
				Scanner input = new Scanner(br);
				principle = input.nextDouble();
				if (principle <= 0.0) {
					System.out
							.println("Error:  Loan Amount must be greater than $0.00");
					continue; // This causes the loop to continue without
					// executing statements after this code
				}
				// Set the local variable to the class level variable
				this.dAmount = principle;
				// set goodNumber to true if no exception to let program
				// continue
				goodNumber = true;
			} catch (Exception e) {
				System.out
						.println("Error: The entered number is invalid or not a number. Please enter a valid number.");
			}
		}

		System.out
				.println("Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:");
		try {
			userChoice = br.readLine();
			if (userChoice == null || "".equals(userChoice.trim())) {
				System.out
						.println("No input provided. By default the report will not be shown ");
			} else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
					.equalsIgnoreCase(userChoice))) {
				System.out
						.println("Invalid input provided. By default the report will not be shown ");
			} else if ("Yes".equalsIgnoreCase(userChoice)) {
				showReport = true;
			}
			// The else condition of userChoice="No" is already covered with
			// intitialization
		} catch (IOException ioe) {
			System.out.println("IOException while reading input: "
					+ ioe.getMessage());
		}
	}

	/**
	 * Function to process the output
	 */
	public void process() {
		DecimalFormat f = new DecimalFormat("$###,###.00");
		double payment;

		// if statement to ensure user enters amount greater than 0
		if (this.dAmount > 0)

		{
			// informs user of desired loan amount
			System.out.println("\nLoan Amount = " + f.format(this.dAmount));

			// displays calculator headings
			System.out
					.println("\n\n*****************************************************");
			System.out.println("* Loan Term " + "\tInterest Rate"
					+ "\tMortgage Payment    *");
			System.out
					.println("*****************************************************");
			// begins loop to determine terms, rates, and payments
			char c = 160;
			for (int i = 0; i < dInterest.length; i++) {
				// calculations to determine payment
				payment = this.dAmount
						* ((dInterest[i] / 12) / (1 - Math.pow(
								1 / (1 + (dInterest[i] / 12)),
								((iTerm[i]) * 12))));
				// displays term in years, interest rates, and payments
				System.out.println((iTerm[i]) + "  years" + "\t" + ((dInterest[i]) * 100) + "%" + "\t\t" + f.format(payment).replaceAll

(""+c,","));
			}

			System.out.println();

			if (this.showReport) {
				// Call function to show the mortgage schedule
				showMortagageSchedule();
                 


			}
		}
	}
}

Open in new window

0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26167023
I have cleaned up a little bit in your code, could you show the formula you use to calculate the monthly interest?

This is how I would do it - First year:
((200000 * 1.0575) - 200000) / 12
200000 * 1.0575 = 211500
211500 - 200000 = 11500
11500 / 12 = 958,33
/**
 Programming 420 Week133 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Week133 {

	// Declaring and constructing variables
	private int[] iTerm = {7, 15, 30};
        private int[] iMonth = {84, 180, 360}; 
	private double[] dInterest = {.0535, .055, .0575};
	private double dAmount, dMonthlyInterest1,
			dMonthlyInterest2, dMonthlyInterest3, dMonthlyPrinciple,
       			dMonthlyBalance1, dMonthlyBalance2, dMonthlyBalance3;
        private double[] dPayment = new double[3];
	DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

	private boolean showReport = false;

	/**
	 * Default constructor
	 */
	public Week133() {
	}

	/**
	 * The main function for the mortgage calculator
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// Create an object of Week133 to process the Mortgage
		Week133 mortgageCalculator = new Week133();
		mortgageCalculator.acceptInput();
		mortgageCalculator.process();
	}

	/**
	 * Function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @return
	 */
	private double MonthlyInterest(double amount, double interestRate) {
		// Declaring Variables for interest on the loan
		double dMonthlyInterest = 0.0;
		// Calculation for monthly interest
		dMonthlyInterest = (amount / 12) * (interestRate / 100);
		return dMonthlyInterest;
	}


	/**
	 * function for the calculation of the monthy loan balance
	 * 
	 * @param amount
	 * @param monthlyPayment
	 * @return
	 */
	private double monthlyBalance(double amount, double monthlyPayment) {
		// Declaring Variables for monthly loan balance
		double dMonthlyBalance = 0.0;
		// Calculations for monthly loan balance
		dMonthlyBalance = (amount - monthlyPayment);
		if (dMonthlyBalance <= 0) {
			dMonthlyBalance = 0.0;
		}
		return dMonthlyBalance;
	}

	/**
	 * Function to show the Mortagage Schedule
	 */
	private void showMortagageSchedule() {
		// output for month to years
		for (int i : iTerm)
                
			System.out.println(String.format(
					"An %1$s-month loan equals a %2$s-year loan.", i, i / 12));

		System.out.println();
		System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
				"Term", "Payment", "Monthly Interest", "Monthly Principle",
				"Balance"));
		// Loop for the varying Mortgage Rates and Payments

		// Month counter
		for (int i = 1; i <= 360; i++) {
			for (int p = 0; p <= 2; p++) {
				// Calculation for the monthly mortgage payment

				switch (p) {
				

       case 0:  // 7 year loan
                    if (i <= iMonth[p]) {
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                            dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;


          case 1:  // 15 year loan
                    if (i <= iMonth[p]) {
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

       
        case 2:  // 30 year loan
                    if (i <= iMonth[p]) {
                                        dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

				}

			}
			// Output for the loan information and the monthly payment
			// System.out.println("Your Monthly Payment for a " + iTerm[p] +
			// " month loan of $200,000 at " + dInterest[p] + "% is:" +
			// twoDigits.format(dPayment));
			System.out.println(String.format("%1$s\t%2$10.2f\t%3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f", i, dMonthlyBalance1, 

dMonthlyInterest1, dMonthlyBalance2, dMonthlyInterest2, dMonthlyBalance3, dMonthlyInterest3));
		}
	}

	/**
	 * Function to accept input from user and set it to class level variables
	 */
	public void acceptInput() {

		double principle = 0;
		// begins loop for input error checking
		boolean goodNumber = false; // declares goodNumber as boolean
		String userChoice = "No";

		// open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		// while loop lets try and catch statements determine if an exception
		// requires user to reinput
		while (!goodNumber) {
			// try statement in case of exception such as user entering a string
			try {
				// informs user to enter amount of desired loan
				System.out
						.println("Please enter the loan amount as a number: ");
				// delcares Scanner object
				Scanner input = new Scanner(br);
				principle = input.nextDouble();
				if (principle <= 0.0) {
					System.out
							.println("Error:  Loan Amount must be greater than $0.00");
					continue; // This causes the loop to continue without
					// executing statements after this code
				}
				// Set the local variable to the class level variable
				this.dAmount = principle;
				// set goodNumber to true if no exception to let program
				// continue
				goodNumber = true;
			} catch (Exception e) {
				System.out
						.println("Error: The entered number is invalid or not a number. Please enter a valid number.");
			}
		}

		System.out
				.println("Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:");
		try {
			userChoice = br.readLine();
			if (userChoice == null || "".equals(userChoice.trim())) {
				System.out
						.println("No input provided. By default the report will not be shown ");
			} else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
					.equalsIgnoreCase(userChoice))) {
				System.out
						.println("Invalid input provided. By default the report will not be shown ");
			} else if ("Yes".equalsIgnoreCase(userChoice)) {
				showReport = true;
			}
			// The else condition of userChoice="No" is already covered with
			// intitialization
		} catch (IOException ioe) {
			System.out.println("IOException while reading input: "
					+ ioe.getMessage());
		}
	}

	/**
	 * Function to process the output
	 */
	public void process() {
		DecimalFormat f = new DecimalFormat("$###,###.00");
		double payment;

		// if statement to ensure user enters amount greater than 0
		if (this.dAmount > 0)

		{
			// informs user of desired loan amount
			System.out.println("\nLoan Amount = " + f.format(this.dAmount));

			// displays calculator headings
			System.out
					.println("\n\n*****************************************************");
			System.out.println("* Loan Term " + "\tInterest Rate"
					+ "\tMortgage Payment    *");
			System.out
					.println("*****************************************************");
			// begins loop to determine terms, rates, and payments
			char c = 160;
			for (int i = 0; i < dInterest.length; i++) {
				// calculations to determine payment
				payment = this.dAmount
						* ((dInterest[i] / 12) / (1 - Math.pow(
								1 / (1 + (dInterest[i] / 12)),
								((iTerm[i]) * 12))));
				// displays term in years, interest rates, and payments
				System.out.println((iTerm[i]) + "  years" + "\t" + ((dInterest[i]) * 100) + "%" + "\t\t" + f.format(payment).replaceAll

(""+c,","));
			}

			System.out.println();

			if (this.showReport) {
				// Call function to show the mortgage schedule
				showMortagageSchedule();
                 


			}
		}
	}
}

Open in new window

0
 

Author Comment

by:coldjava
ID: 26167451
Nordtorp --

Thanks for the help.

 I think my formula is: number of years = 7
interest = 2000*(1+5.35/100)^7 = 2880.525 (approx)

Is the code almost ready?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26168185
re: "Also, he told me he was not going to be available until very late tonight. The assignment is due Monday. Apparently he washed his hands of me."
 -- or maybe he's away for the Sunday

re: "he chewed me out for altering my code"
-- I'm assuming the altering was from our suggestions, in which case, he may not be on board with other suggestions. The other suggestions may even be out-of-scope for the class level you are at. The suggestions are suggestions - you, of course, make the ultimate decisions.

I looked at http:#26167023 and I am surprised to see that dPayment[i] is being used, it is defined, but it is never set (if I'm reading this right). Did you step through the results to see what values dPayment[i] has in it?

Take a look at:
    dMonthlyInterest = (amount / 12) * (interestRate / 100);

Why are you dividing amount by 12?
Why are you dividing interestRate by 100?
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26168865
coldjava,

interest = 2000*(1+5.35/100)^7 = 2880.525 (approx)

Shouldn't the interest be something like this the three first months for 7-year loan? 958.33, 957.33 and 956.33

My best tip is to get all the calculations for the first month correct, and then start to do anything else. The essence of the program are calculations.
0
 

Author Comment

by:coldjava
ID: 26173759
Nordtorp --
Thanks for the response.
You recommended another formula.
This is how I would do it - First year:
((200000 * 1.0575) - 200000) / 12
200000 * 1.0575 = 211500
211500 - 200000 = 11500
11500 / 12 = 958,33
Probably best to go with that one.

 
0
 

Author Comment

by:coldjava
ID: 26173998
Phoffric --
Thanks for your response.  
RE: I looked at http:#26167023 and I am surprised to see that dPayment[i] is being used, it is defined, but it is never set (if I'm reading this right). Did you step through the results to see what values dPayment[i] has in it?
No. The instructor told me to insert dPayment[i]. But nothing about how to set. How do I go about settting it?

RE: Take a look at:
    dMonthlyInterest = (amount / 12) * (interestRate / 100);
Why are you dividing amount by 12?
Why are you dividing interestRate by 100?

In answer to this, would each loan (3) have to have a different dMonthlyInterest = (amount /100) * (interestRate .535/12);
previous loan balance 12 monthly interest rate
previous loan balance - (monthly mortagage payment - current month's interest amount)
I am not sure this is exactly correct. I am trying to determine the amount loaned, the interest being changed, and that each year has 12 months. So it would be something like interest amount/months% = 5.35%.  
Also, my instructor stated my private double[] dInterest = {.0535, .055, .0575};
is not correct because the interest rate of 5.35%, 5.5%, and 5.75% have already been divided by 100 to come up with the decimal values.  
Would this mean I should remove this code line? If so, would I replace it with anything else?

Thanks for the help.
 

 
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26174075
dInterest is 5.35 / 100 = 0.0535, you should not need to divide by 100 once more.

In your assignment you don't have anything about the rate being changed, so you should be able to use 0.0535 as a constant.

5.35% is the rate for one year. For a month that would be 5.35 / 12. That is for every month.

As you see in my formula I have used 1.0575, this is because I want to know how much the loan with interest that year is. We then divide the difference between loan with interest and current loan by 12 to get the interest that month.
0
 

Author Comment

by:coldjava
ID: 26174464
Nordtorp --
 
Thanks for the response.  
OK. This formula would be for the 7-year loan.
 
((200000 * 1.0575) - 200000) / 12
200000 * 1.0575 = 211500
211500 - 200000 = 11500
11500 / 12 = 958,33

So would I write my code line as:
 private double[] dInterest = {5.35/100 =0.0535};  

Or would it be written:
 private double[] dInterest = {5.35/100 =0.0535, 5.5/100 =0.055, 5.75/100=0.0575};  

Would this replace the--  private double[] dInterest = {.0535, .055, .0575}; --- near the top of my code?

Thanks again.
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26174510
I would have kept this line:
private double[] dInterest = {.0535, .055, .0575}

Just add a comment to it something like // 5.35% = 0.0535

Just remember to use the correct form then you calculate with these numbers.

In the above formula you have acctually done this: (5.35 / 100) + 1
0
 

Author Comment

by:coldjava
ID: 26174758
Nordtorp --

 Thanks for the reply. I have not changed my code yet.
So I keep:  private double[] dInterest = {.0535, .055, .0575};
and add: // 5.35%=0.0535

In my code would it look like:
private double[] dInterest = {.0535, .055, .0575}; // 5.35%=0.0535
private double[] dInterest = (5.35/100) + 1

Then would I need to do this for the other loans too?

My instructor pointed out that I needed to fix this. Here is his exact wording:
The first thing to fix is your monthly interest percent:
1. Your monthly interest rate is not computed correctly. In your code
private double[] dInterest = {.0535, .055, .0575};
The interest rate of 5.35%, 5.5% and 5.75% have laready been divided by 100 to come up with the decimal values.
In your MonthlyInterest method, the equation
dMonthlyInterest = (amount /12) * (interestRate / 100); is not correct.

 I also, need help on how to set dPayment = payment.

Thanks for the help. I am sorry I am such a dummy.
     
0
 

Author Comment

by:coldjava
ID: 26175020
Nordtorp --
 
Something I did not add in my other post. Would setting the dPayment = payment look like this:

 dPayment = Pmt(dRate / 12, iYears * 12, -1 * dLoan)

 or would it need to be amended to match each loan year -- 7, 15, and 30?
 If so, would it look like this:
dPayment = Pmt(dRate / 12, iYears * 7, -1 * dLoan)
dPayment = Pmt(dRate / 12, iYears * 15, -1 * dLoan)
dPayment = Pmt(dRate / 12, iYears * 30, -1 * dLoan)

Thanks.




 


0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26175141
First of all, how long have you been learning java?

1. private double[] dInterest = {.0535, .055, .0575}; // 5.35%=0.0535
2. private double[] dInterest = (5.35/100) + 1

In line 1 you say dInterest is a array and has three values, 0.535, 0.055 and 0.0575,
Then in line 2 you say dInterest is a array and has one value.

Line to should not be used.

The float of your program should be like this (only calculations)
1. Find out mortgage payment (number around 1500-2500)
2. Find interest Paid (number starting on about 950)
3. Find new balance after mortgage payment. (loan + interest - mortgage)
4. Set new balance

I went through your code once more and you are doing something really wrong some place. I feel you have too much calculations there. Try starting over with your calculations. Try to just get the first month correct, when that is correct, you could go further.
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26175165
Could you first tell me what payment should represent?
0
 

Author Comment

by:coldjava
ID: 26175296
Nordtorp --

 I got confused. This was your message:

In the above formula you have actually done this: (5.35 / 100) + 1

So I thought (5.35/100) + 1 needed to be included.

This paragraph you wrote has me worried:
"I went through your code once more and you are doing something really wrong some place. I feel you have too much calculations there. Try starting over with your calculations. Try to just get the first month correct, when that is correct, you could go further."

From this I do not know if you cannot tell me what is wrong based on EE rules, or you have been unable to locate the problem yourself. If an expert cannot find the problem I doubt seriously that I can.

Thanks for all your help.
0
 

Author Comment

by:coldjava
ID: 26175342
Nordtorp --

 Thanks for the reply. I believe it is the monthly payments for paying off the loans.  
 The payments start with the 7 year loan, followed by the 15 year loan and finally the 30 year loan.
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26175556
The monthly payments is always the mortgage payment, that will not change. Therefore when you have got the mortgage payment correct you save it to payment7, payment15 and payment30, or payment[0], payment[1] and payment[2]. Depends on what you want to have; three variables or an array.

What I meant (5.35 / 100) + 1 was that I had to use 1.0535 to get the numbers correct.

I would recommend you to study my code in comment #26161924 and try to understand what I have done. Then try to apply what you understood to your code.

When I have code that don't do what I want, I try to do one out of many things:
1. Comment out most of my code and create new code, maybe new variables too
2. Start over again
3. Write small programs to do one operation at a time.
4. Try to find another way to solve my problem, other algorithms and so on.

I think you have studied your own code too long, and should look for other methods and/or ways to do what you to do.

Try to do something like this (just an example with untested code):

void main ()
{
double loan = 200000.0;
double mortgagePayment = 2859.79;
double rate = 5.35;

// do something to find interestPaid
}
0
 

Author Comment

by:coldjava
ID: 26176138
Nordtorp --

 Thanks for the suggestions.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26176634
Could you resubmit your current running program to get me up to date.
0
 

Author Comment

by:coldjava
ID: 26176849
Nordtorp --

My instructor told me a little while ago that I only needed a little more work to get my code to operate properly. Good news! He also told me to continue getting help from a tutor.

Anyway here were his suggestions:
1.  Inside method process, right after payment is calculated, put
    dPayment = payment;

You want the dPayment array to have values, so that they can be used outside method process.

Coldjava Question 1. Can you tell me where is the method process located in my code?


2.  Look at your code to compute the monthly interest below:

dMonthlyInterest = (amount / 12) * (interestRate / 100);


The equation in pseudo code is:

Monthly interest = previous loan balance x monthly interest rate

Coldjava Question 2. By previous loan balance would this be written three times to cover each interest rate:

  dMonthlyInterest = (amount 200000/535) * (interestRate 535/12%);
            return dMonthlyInterest;
   dMonthlyInterest = (amount 200000/55) * (interestRate 55/12%);
            return dMonthlyInterest;;    
dMonthlyInterest = (amount 200000/575) * (interestRate 575/12%);
            return dMonthlyInterest;

Monthly interest = previous loan balance x annual interest rate /12

Thanks for the assistance.
0
 

Author Comment

by:coldjava
ID: 26177009
Phoffric --

Thanks for the response.

I have attempted to alter the following line and I am getting error messages:

dMonthlyInterest = (amount / 12) * (interestRate / 100);

I have tried using:
dMonthlyInterest = (amount 200000/535) * (interestRate 535/12%);

 Thanks again.
/**
 Programming 420 Week65 Mortgage Calculator by Williams
 */

//The java.io package provides for system input and output through data streams
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Week65 {

	// Declaring and constructing variables
	private int[] iTerm = {7, 15, 30};
        private int[] iMonth = {84, 180, 360}; 
	private double[] dInterest = {.0535, .055, .0575};
	private double dAmount, dMonthlyInterest1,
			dMonthlyInterest2, dMonthlyInterest3, dMonthlyPrinciple,
       			dMonthlyBalance1, dMonthlyBalance2, dMonthlyBalance3;
        private double[] dPayment = new double[3];
	DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

	private boolean showReport = false;

	/**
	 * Default constructor
	 */
	public Week65() {
	}

	/**
	 * The main function for the mortgage calculator
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// Create an object of Week65 to process the Mortgage
		Week65 mortgageCalculator = new Week65();
		mortgageCalculator.acceptInput();
		mortgageCalculator.process();
	}

	/**
	 * Function for the calculation of the interest into the loan payment
	 * 
	 * @param amount
	 * @param interestRate
	 * @return
	 */
	private double MonthlyInterest(double amount, double interestRate) {
		// Declaring Variables for interest on the loan
		double dMonthlyInterest = 0.0;
		// Calculation for monthly interest
		dMonthlyInterest = (amount / 12) * (interestRate / 100);
		return dMonthlyInterest;
	}


	/**
	 * function for the calculation of the monthy loan balance
	 * 
	 * @param amount
	 * @param monthlyPayment
	 * @return
	 */
	private double monthlyBalance(double amount, double monthlyPayment) {
		// Declaring Variables for monthly loan balance
		double dMonthlyBalance = 0.0;
		// Calculations for monthly loan balance
		dMonthlyBalance = (amount - monthlyPayment);
		if (dMonthlyBalance <= 0) {
			dMonthlyBalance = 0.0;
		}
		return dMonthlyBalance;
	}

	/**
	 * Function to show the Mortagage Schedule
	 */
	private void showMortagageSchedule() {
		// output for month to years
		for (int i : iTerm)
                
			System.out.println(String.format(
					"An %1$s-month loan equals a %2$s-year loan.", i, i / 12));

		System.out.println();
		System.out.println(String.format("%1$s%2$10s%3$20s%4$20s%5$10s",
				"Term", "Payment", "Monthly Interest", "Monthly Principle",
				"Balance"));
		// Loop for the varying Mortgage Rates and Payments

		// Month counter
		for (int i = 1; i <= 360; i++) {
			for (int p = 0; p <= 2; p++) {
				// Calculation for the monthly mortgage payment

				switch (p) {
				

       case 0:  // 7 year loan
                    if (i <= iMonth[p]) {
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                            dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;


          case 1:  // 15 year loan
                    if (i <= iMonth[p]) {
                    dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

       
        case 2:  // 30 year loan
                    if (i <= iMonth[p]) {
                                        dMonthlyInterest1 = MonthlyInterest(dAmount,
                    dInterest[p] / 12);
                    dMonthlyPrinciple = (dPayment[p] - dMonthlyInterest1);
                    dMonthlyBalance1 = monthlyBalance(dAmount,
                            dMonthlyPrinciple);
                    dAmount = dMonthlyBalance1;
                    }
                    else {
                      dMonthlyBalance1 = 0.0;
                      dMonthlyInterest1 = 0.0;
                    }
                    break;

				}

			}
			// Output for the loan information and the monthly payment
			// System.out.println("Your Monthly Payment for a " + iTerm[p] +
			// " month loan of $200,000 at " + dInterest[p] + "% is:" +
			// twoDigits.format(dPayment));
			System.out.println(String.format("%1$s\t%2$10.2f\t%3$10.2f\t%4$10.2f\t%5$10.2f\t%6$10.2f\t%7$10.2f", i, dMonthlyBalance1, 

dMonthlyInterest1, dMonthlyBalance2, dMonthlyInterest2, dMonthlyBalance3, dMonthlyInterest3));
		}
	}

	/**
	 * Function to accept input from user and set it to class level variables
	 */
	public void acceptInput() {

		double principle = 0;
		// begins loop for input error checking
		boolean goodNumber = false; // declares goodNumber as boolean
		String userChoice = "No";

		// open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		// while loop lets try and catch statements determine if an exception
		// requires user to reinput
		while (!goodNumber) {
			// try statement in case of exception such as user entering a string
			try {
				// informs user to enter amount of desired loan
				System.out
						.println("Please enter the loan amount as a number: ");
				// delcares Scanner object
				Scanner input = new Scanner(br);
				principle = input.nextDouble();
				if (principle <= 0.0) {
					System.out
							.println("Error:  Loan Amount must be greater than $0.00");
					continue; // This causes the loop to continue without
					// executing statements after this code
				}
				// Set the local variable to the class level variable
				this.dAmount = principle;
				// set goodNumber to true if no exception to let program
				// continue
				goodNumber = true;
			} catch (Exception e) {
				System.out
						.println("Error: The entered number is invalid or not a number. Please enter a valid number.");
			}
		}

		System.out
				.println("Do you see want to view the amortization 7 column table or not? Respond with Yes/No and click <ENTER> key:");
		try {
			userChoice = br.readLine();
			if (userChoice == null || "".equals(userChoice.trim())) {
				System.out
						.println("No input provided. By default the report will not be shown ");
			} else if (!("Yes".equalsIgnoreCase(userChoice) || "No"
					.equalsIgnoreCase(userChoice))) {
				System.out
						.println("Invalid input provided. By default the report will not be shown ");
			} else if ("Yes".equalsIgnoreCase(userChoice)) {
				showReport = true;
			}
			// The else condition of userChoice="No" is already covered with
			// intitialization
		} catch (IOException ioe) {
			System.out.println("IOException while reading input: "
					+ ioe.getMessage());
		}
	}

	/**
	 * Function to process the output
	 */
	public void process() {
		DecimalFormat f = new DecimalFormat("$###,###.00");
		double payment;

		// if statement to ensure user enters amount greater than 0
		if (this.dAmount > 0)

		{
			// informs user of desired loan amount
			System.out.println("\nLoan Amount = " + f.format(this.dAmount));

			// displays calculator headings
			System.out
					.println("\n\n*****************************************************");
			System.out.println("* Loan Term " + "\tInterest Rate"
					+ "\tMortgage Payment    *");
			System.out
					.println("*****************************************************");
			// begins loop to determine terms, rates, and payments
			char c = 160;
			for (int i = 0; i < dInterest.length; i++) {
				// calculations to determine payment
				payment = this.dAmount
						* ((dInterest[i] / 12) / (1 - Math.pow(
								1 / (1 + (dInterest[i] / 12)),
								((iTerm[i]) * 12))));
				// displays term in years, interest rates, and payments
				System.out.println((iTerm[i]) + "  years" + "\t" + ((dInterest[i]) * 100) + "%" + "\t\t" + f.format(payment).replaceAll

(""+c,","));
			}

			System.out.println();

			if (this.showReport) {
				// Call function to show the mortgage schedule
				showMortagageSchedule();
                 


			}
		}
	}
}

Open in new window

0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26178189
See this line:
dMonthlyInterest = (amount 200000/535) * (interestRate 535/12%);

What are you doing here "interestRate 535/12%"

You have to put something between interestRate and 535/12%.

I don't even think 12% is correct.
0
 

Author Comment

by:coldjava
ID: 26181601
Nordtorp --

Thanks for the reply. My instructor gave me instructions and an example. He stated if someone borrowed money say $1000 and was charged 10% interest per year. With 12 months to each year the monthly interest rate would be 10/12% = 8.33%. "

 He put the % after the 12 months in the year. I tried to follow this.

 Then provided this: "Look at your code to compute the monthly interest below:

dMonthlyInterest = (amount / 12) * (interestRate / 100);

The equation in pseudo code is:

Monthly interest = previous loan balance x monthly interest rate

Monthly interest = previous loan balance x annual interest rate /12

I have to write the pseudo code but turn it into Java code.

From his instructions I thought I on the right track.

So would I instead write: dMonthlyInterest = (amount 200000/535) * (interestRate197141/ 535);
 
The $2859.79 is the Mortgage Payment from the 7 year loan displayed in the "No" portion of this assignment. Should I subtract 2859.79 from 200000 and use that figure in the InterestRate.

Is this correct? And would I need to write two more such code lines to incorporate the 15 year loan and the 30 year loan?


0
 
LVL 11

Accepted Solution

by:
nordtorp earned 2000 total points
ID: 26184083
You are almost there, but still a little far away.

Let me explain.

You borrow $200,000 and have agreed to pay 2859.79 each month.

Because the yearly interest rate is 5.35 %, you have to find out how much interest that have become of $200,000 in one month, because you pay back a little.

The first year interest will be 10700, because $200,000 + 5.35 % is 10700. But because you have just borrowed for a month the interest have just been going on for a month and you have to calculate how much 10700 would be for one month. As in 10700 / 12 = 891,67 (familiar with the number?)

Monthly Interest is previous loan balance * annual interest rate / 12, this is your pseudo code.

In math that would be something like this:
monthlyInterest =  200000 + 5,35% / 12
or
monthlyInterest = 200000 * (5.35/100) / 12
also known as
monthlyInterest = 200000 * 0.0535 / 12


In java it would be this:
monthlyInterest = 200000 * 5,35

--------------------------------------------

To get the reamining loan after first payment:

Pseudo:
Balance after payment is my loan and interest together minus what I paid last month

In math:
Remaining loan = loan + interest - payment
Remaining loan = 200000 + 891.67 - 2859.79

In java:
RemLoan = loan + interestRate - mortgagePayment

I hope this help you a little bit. Good luck!
0
 

Author Comment

by:coldjava
ID: 26186878
Nordtorp --

Thanks for the detailed assistance. It is much appreciated.

I have entered two lines of code based on what I think you were telling me. Can you tell me if it is accurate?

private double MonthlyInterest(double amount, double interestRate) {
            // Declaring Variables for interest on the loan
            double dMonthlyInterest = 0.0;
            // Calculation for monthly interest
            
                dMonthlyInterest = 20000 * 5.35;  <-------------------------------------------new line
                dmonthlyBalance = 189300 = 200000 + 5.35 - 2859.79;    <---------------new line
            
               return dMonthlyInterest;


Do I need to do the same for the 15 year loan and the 30 year loan too?

Thanks.
0
 

Author Closing Comment

by:coldjava
ID: 31670138
Provided a lot of detailed explanations.
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26195011
That seems to be some what correct, but monthlyInterest should be 200000 * 5.35 / 100 / 12; or else you get yearlyInterest.
or said in another way 200000 * 5.35 / 1200; would also be monthlyInterest

monthlyBalance should be:

monthlyBalance = 200000 + monthlyInterest - mortgagePayment.
0
 

Author Comment

by:coldjava
ID: 26195696
Nordtorp --

 Thanks.

 Specifically, I need to insert  monthlyInterest = 200000 * 5.35 / 100 / 12;

                                               monthlyBalance = 200000 + 5.35 - 10700
 
 Do I need to do this on the 15 year loan and the 30 year loan?

                                               monthlyInterest = 200000 * 5.5 / 100 / 12;

                                               monthlyBalance = 200000 + 5.5 - 11000

                                               monthlyInterest = 200000 * 5.75 / 100 / 12;

                                               monthlyBalance = 200000 + 5.75 - 11500

0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26202145
coldjava, that was not quite right.
monthlyInterest were correct, keep that.

When it comes to monthlyBalance. Have you tried to do those calculations on a calculator?
I think you should do this:

monthlyBalance = 200000 + monthlyInterest - mortgagePayment(2859.79)
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26202155
I am sorry if I am confusing you.

monthlyBalance = 200000 + 891.67 - 2859.79. Insert the corresponding values for 15 and 30-year loans.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
In this post we will learn different types of Android Layout and some basics of an Android App.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

862 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