# formula for mortgage calc. Numerator/Denominator with no values.

Page 1 of 1

## 10 Replies - 902 Views - Last Post: 29 March 2013 - 08:01 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=284162&amp;s=b8190ec8bb5d344ac65a8b532baebe94&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 DoubleM

Reputation: 0
• Posts: 10
• Joined: 26-June 12

# formula for mortgage calc. Numerator/Denominator with no values.

Posted 27 June 2012 - 09:52 PM

ok, for my first question... it's the fabled mortgage calculator yet once again.

as you can see, I broke the formula down, testing values at each step with print commands. the values did display. However, getting to line #71 states that "the assigned value is never used". I'm simultaneously running a previous version that does correctly calculate and output...but the code is identical. So...can anyone see something I'm overlooking?
-DoubleM

```inputRate = loanScanner.nextDouble ( );   //Accepts entered APR.
if (inputRate != (termRate[i]) ){   //Validates input. Begin If statement.
out.println("Sorry, you entered an invalid option for the APR . Please try again.");

//                    if (inputRate == termRate[i]){

//                    if (inputYears == termYear[i] && inputRate == termRate [i]){
} else {    // Close If, Begin Else

monthlyInterestRate = termRate[i]/ 100 / 12;  //termRate==annualInterestRate
out.println("monthly interest rate is " + monthlyInterestRate); //display tests values.
//Divide interestRate by 100 to return decimal value. termRate[i]/ 100 / 12=
//Divide the results by 12 to return the monthly intest rate.
termMonths = termYear[i] * 12; //obtains months from 7,15 & 30 yr.terms.
//Find the numerator of the formula.Multiply the monthlyInterestRate by principleAmount.

out.println("term months equals" + termMonths);  //tests output of termMonths value. It works.

formulaNumerator = (monthlyInterestRate * principleAmount);
//Solve for Denominator by using Javas' .pow function.
out.println (" the numerator is " + formulaNumerator); //tests vaue. it works.

formulaDenominator = 1 - (java.lang.Math.pow((1 + monthlyInterestRate), (-1 * termMonths)));
out.println("the denominator is" + formulaDenominator); //tests value. works.

// Display formatted payment amount

out.println("Your mortgage principle of " + sprincipleAmount
+ " for " + termYear[i] +" years at " + termRate[i] + "% APR comes to "
+ smonthlyPayment + " monthly. \n");

for (int k=0; k < 3; k++){  //Begin For Loop
}

```

Is This A Good Question/Topic? 0

## Replies To: formula for mortgage calc. Numerator/Denominator with no values.

### #2 JorgenG

Reputation: 12
• Posts: 39
• Joined: 24-January 10

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 27 June 2012 - 10:36 PM

First thing I see is no closing bracket for the else on line 8.

But I suspect you have only given us part of your code, which makes it very hard to to know where your line 71 is..

### #3 fromTheSprawl

• Wandering Like A Fool

Reputation: 509
• Posts: 2,041
• Joined: 28-December 10

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 27 June 2012 - 10:49 PM

Are you somehow using Eclipse? That is a very common message when you do something like declaring a variable, but not doing anything with other than giving it a value. We appreciate it if you can point out line 71 too.

### #4 pbl

• There is nothing you can't do with a JTable

Reputation: 8032
• Posts: 31,202
• Joined: 06-March 08

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 28 June 2012 - 03:50 AM

Too much is like not enough
Group your comments together and put a few lines of code together

``` for (int k=0; k < 3; k++){  //Begin For Loop

```

do you seriously think that // Begin for loop is a useful comment ?
// loop for the 3 interest rates would be though

### #5 DoubleM

Reputation: 0
• Posts: 10
• Joined: 26-June 12

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 28 June 2012 - 07:02 PM

pbl, on 28 June 2012 - 03:50 AM, said:

Too much is like not enough
Group your comments together and put a few lines of code together

``` for (int k=0; k < 3; k++){  //Begin For Loop

```

do you seriously think that // Begin for loop is a useful comment ?
// loop for the 3 interest rates would be though

### #6 DoubleM

Reputation: 0
• Posts: 10
• Joined: 26-June 12

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 28 June 2012 - 07:15 PM

I'm just now getting the opportunity to get back to work on this. Ok,... I didn't post all of my code the first time, because I assumed for the site rule of "no homework"...that a little ...and not all of it would be ok. That was my reasoning for that. To the point, I've cleaned up the code a little. Here it is again ...all of it. In regards of useful comments, I admit, I'm super-green and it was to help me keep my head around the structure of the program. I can handle the critique. It's cool.

Thanks Again
-DoubleM

```
import static java.lang.System.out;
import java.text.NumberFormat;
import java.util.Scanner;

//  @author Matthew

public class MayArray {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int    principleAmount = 200000;    // Variable Declaration Statements
int    termMonths = 0;

int    i=0;
int    j=0;
int    inputYears=0;
double monthlyInterestRate = 0;
double formulaNumerator = 0;
double monthlyPayment = 0;
double inputRate=0;

NumberFormat currency = NumberFormat.getCurrencyInstance();
String sprincipleAmount = currency.format(principleAmount);
String smonthlyPayment = currency.format(monthlyPayment);   //formatted Variables.

int termYear [] = {7,15,30};  //Declaring  and Store Values in Array indexes.
double termRate [] = {5.35, 5.5, 5.75};

out.println("For your principle amount of \$200,000.00, enter the  loans' term of years.");//user prompt

Scanner loanScanner = new Scanner (System.in);		//initialize Scanner.
inputYears = loanScanner.nextInt ( );

if (inputYears!= (termYear[i]))  {     //Validates user input
out.println("Sorry, you entered an invalid option for the term of years: 7, 15 or 30. Please try again.");//Error Message to User
} else {

if (inputYears == (termYear[i])) { //
out.println("Next, please enter the Annual Percentage Rate of the loan. (without percentage symbols)");//user prompt

inputRate = loanScanner.nextDouble ( );   //Accepts entered APR.
if (inputRate != (termRate[i]) ){   //Validates input.
out.println("Sorry, you entered an invalid option for the APR . Please try again.");

} else {

monthlyInterestRate = termRate[i]/ 100 / 12;
out.println("monthly interest rate is " + monthlyInterestRate); //display tests values.

termMonths = termYear[i] * 12;
//Determines the numerator of the formula.

out.println("term months equals" + termMonths);  //tests output of termMonths value. It works.

formulaNumerator = (monthlyInterestRate * principleAmount);
//Solve for Denominator by using Javas' .pow function.
out.println (" the numerator is " + formulaNumerator); //tests vaue. it works.

formulaDenominator = 1 - (java.lang.Math.pow((1 + monthlyInterestRate), (-1 * termMonths)));
out.println("the denominator is" + formulaDenominator); //tests value. works.

// Display formatted payment amount

out.println("Your mortgage principle of " + sprincipleAmount
+ " for " + termYear[i] +" years at " + termRate[i] + "% APR comes to "
+ smonthlyPayment + " monthly. \n");

for (int k=0; k < 3; k++){  //For Loop for the 3 interest rates.
}
} //End Else #2
}  // Close If #2
}   //Close Else #1
}   //Close Main
}//Close Class

```

### #7 DoubleM

Reputation: 0
• Posts: 10
• Joined: 26-June 12

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 28 June 2012 - 08:49 PM

Alright. Progress. I got it, but I need an expert explanation of ..why my changes worked. In the code posted earlier, String variables: sprincipleAmount & smonthlyPayment are declared in lines 26 and 27. I noticed in the other working version, that these variables were declared on lines 68 and 69. This fixed the errors and gave values back to the Numerator/Denominator and now calculates just fine.
What does declaring these inside the calculation statements mean? I'm vaguely familiar with static and non-static variables. Is this what happened?...Is my train of thought on the right track?

Thanks!
-Matt

### #8 fromTheSprawl

• Wandering Like A Fool

Reputation: 509
• Posts: 2,041
• Joined: 28-December 10

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 28 June 2012 - 10:25 PM

On your working code, you gave the value of monthlyPayment to smonthlyPayment on line 27. At that point, monthlyPayment only has 0 for its value. The other code worked I presume because you gave the value of monthlyPayment to smonthlyPayment after you've performed an operation to the former, which gives it a value other than 0.

Further example:

```int x = 0; // x is zero
int y = x; // you give the value of x to y, which is currently 0
x = 1 + 2; // x now has 3 for its value
System.out.println(y); // will print 0, because that's what it's holding at the time you assigned a value to it

```

The way to do it is to give your variable which you want to print the value of another variable once you performed all the operations you need on that one.
```int x = 0; // x is zero
x = 1 + 2; // x now has 3 for its value
int y = x; // y will now have 3 for its value
System.out.println(y); // will print 3

```

The placing of your assignment of values counts. By the way, when DIC says we will not do your homework, it means the more code you show, the better.

### #9 DoubleM

Reputation: 0
• Posts: 10
• Joined: 26-June 12

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 29 June 2012 - 09:44 AM

Good morning. I'm back.
Still working with the same code. Now that the Num/Denom' issue is fixed and I do understand why now ... ( still haven't gotten a reply from my professor on that question.) This is another common, simple issue (for others) that plagues a lot of Java-newbies like me.

Currently, the program recognizes only the first index of each array as valid input. It does not see termYears[15] or [30] or their paired termRates[i] at all. I was thinking that...as is, it doesn't have a way to collect for the other indexes before it jumps straight into checking those conditions with all the IF/Else statements.

So, I put a For Loop at the top, before those conditions on line 37 so it could iterate through the idexes, checking the users input. And a new error. "i is already defined in java.lang." which I fully agree with and understand, because I declared it at line 16. I also declared a "j" at line 17, though I do not know why.
So, to experiment, I comment i out at line 16 which produces the error "can not find variable i" ...which is used to refer to all of my instances of the termYear[i] and termRate[i]. ...

This is where we newbies can get discouraged because the original issue was to find 15 & 30 and errors generate errors and now torn between the declaration of my variables.
Look.. I know this is such a simple, crayon-fix for many more advanced Java-tiers ...but this is my challenge for the moment that I'm ready to understand and move beyond it. Any additional insight and guidance is appreciated.
Please overlook the comments at the bottom. These are just additional attributes I want to later add, but you see where I want to go with its functionality.
```import static java.lang.System.out;
import java.text.NumberFormat;
import java.util.Scanner;

//  @author Matthew

public class MayArray {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int    principleAmount = 200000;    // Variable Declaration Statements
int    termMonths = 0;

//        int    i=0;
int    j=0;
int    inputYears=0;
double monthlyInterestRate = 0;
double formulaNumerator = 0;
double monthlyPayment = 0;
double inputRate=0;
char   y = 0;

NumberFormat currency = NumberFormat.getCurrencyInstance();

int termYear [] = {7,15,30};  //Declaring  and Store Values in Array indexes.
double termRate [] = {5.35, 5.5, 5.75};

out.println("Hello and welcome to McBride Financials' new mortgage calculator.");
out.println("For your principle amount of \$200,000.00, enter the  loans' term of years.");//user prompt

Scanner loanScanner = new Scanner (System.in);		//initialize Scanner.
inputYears = loanScanner.nextInt ( );

for (int i=0; i < 3; i++){  //For Loop for the 3 interest rates.
}
if (inputYears!= (termYear[i]))  {     //Validates user input
out.println("Sorry, you entered an invalid option for the term of years: 7, 15 or 30. Please try again.");//Error Message to User
} else {

if (inputYears == (termYear[i])) { //
out.println("Next, please enter the Annual Percentage Rate of the loan. (without percentage symbols)");//user prompt

inputRate = loanScanner.nextDouble ( );   //Accepts entered APR.
if (inputRate != (termRate[i]) ){   //Validates input.
out.println("Sorry, you entered an invalid option for the APR . Please try again.");

} else {

for (int k=0; k < 3; k++){  //For Loop for the 3 interest rates.
}
monthlyInterestRate = termRate[i]/ 100 / 12;  //termRate==annualInterestRate

//Divide interestRate by 100 to return decimal value. termRate[i]/ 100 / 12=
//Divide the results by 12 to return the monthly intest rate.
termMonths = termYear[i] * 12; //obtains months from 7,15 & 30 yr.terms.

//Find the numerator of the formula.Multiply the monthlyInterestRate by principleAmount.
formulaNumerator = (monthlyInterestRate * principleAmount);

//Solve for Denominator by using Javas' .pow function.
formulaDenominator = 1 - (java.lang.Math.pow((1 + monthlyInterestRate), (-1 * termMonths)));
// Display formatted payment amount

String sprincipleAmount = currency.format(principleAmount);
String sMonthlyPayment = currency.format(monthlyPayment);
out.println("Your mortgage principle of " + sprincipleAmount
+ " for " + termYear[i] +" years at " + termRate[i] + "% APR comes to "
+ sMonthlyPayment + " monthly. \n");

out.println("Would you like to calculate for another term loan?");
out.println("Enter Y for 'yes' or Esc to Exit the loan calculator.");

//            public static boolean [yes] ( [char] ['y'] );
//            boolean yes = true;
//            char    yes = new char('y')
//      {
//            yes=false;
//      }
//      return yes;
// }
//            .compareTo();
//            if..
//            boolean input.nextChar == 'y';
//            while (what are my conditions? )
// outputs the payment for three loans
// loan terms and rates are in array variables
//            for (int i=0; i<=2; i++){
//
//            monthlyInterestRate = termRate/ 100 / 12;
//            termMonths = termYear * 12;
//
//            // calculate the payment (calculate the numerator and denominator first)
//            formulaNumerator = (monthlyInterestRate * principleAmount);
//            formulaDenominator = 1 - (java.lang.Math.pow((1 + monthlyInterestRate), (-1 * termMonths)));
//
//            monthlyPayment = formulaNumerator / formulaDenominator;
//
//            // Display formatted payment amount
//            sPrincipleAmount = currency.format(principleAmount);
//            sMonthlyPayment = currency.format(monthlyPayment);
//            out.println("Your mortgage principle of " + sPrincipleAmount
//                + " for " + termYear +" years at " + termRate + "% APR comes to "
//                + sMonthlyPayment + " monthly. \n");
//
//        } // end for loop

} //End Else #2
}  // Close If #2
}   //Close Else #1
}   //Close Main
}//Close Class

```

### #10 GregBrannon

• D.I.C Lover

Reputation: 1987
• Posts: 4,840
• Joined: 10-September 10

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 30 June 2012 - 01:29 AM

In general programming terms, variables have a characteristic known as "scope" which defines their "visibility" or "accessibility" at any point in the program. The Java terms that describe a variable's scope are "fields," "local variables," and "parameters." You can find more discussion and the meaning of these terms at this link in the Java Tutorials.

To your specific problem: at line 16 you commented out the declaration and initialization of the variable i. This 'i' would be a "local variable" to the main() method. The scope of this 'i' would be the main() method. The same can be said for all of the variables in lines 13 - 24. (This style of declaring and initializing all variables at the beginning of a program or method is common in C programming. The Java convention is to declare and initialize variables as they're needed and/or as necessary to provide the required scope.)

At line 37 you defined another local variable called 'i':
```for (int i=0; i < 3; i++){  //For Loop for the 3 interest rates.
}
```

I moved the closing brace to the left to more clearly show that the for clause is empty. The local variable 'i' would be visible inside the for loop, but the for loop is empty. The local variable 'i' declared/initialized in the for loop would be visible to the statements that follow it, IF you moved the closing brace of the for loop to include those statements. I have shown that below, moving the closing brace of the for loop to the bottom with the other close braces. I cut out some of your code to simplify my point, but I ended with the for loop that uses the control variable 'k' to show that it is also an empty loop.
```//For Loop for the 3 interest rates.
for (int i=0; i < 3; i++)
{
//Validates user input
if (inputYears!= (termYear[i]))
{
out.println("Sorry, you entered an invalid option for the term of years: 7, 15 or 30. Please try again.");//Error Message to User
}
else
{
if (inputYears == (termYear[i]))
{
out.println("Next, please enter the Annual Percentage Rate of the loan. (without percentage symbols)");//user prompt

inputRate = loanScanner.nextDouble ( );   //Accepts entered APR.

//Validates input.
if (inputRate != (termRate[i]) )
{
out.println("Sorry, you entered an invalid option for the APR . Please try again.");

}
else
{
for (int k=0; k < 3; k++)
{  //For Loop for the 3 interest rates.

}

// etc . . . .

} //End Else #2
}  // Close If #2
}   //Close Else #1
}	// End for loop with 'i'
```

One final point that may confuse you, but it's important for completeness: Since the for loop using the 'i' control variable is inside the main() method, it COULD use the 'i' declared at line 16:
```public static void main(String[] args)
{
// all of the other variables
int    i=0;  // uncommented line 16
//For Loop for the 3 interest rates.
for (i=0; i < 3; i++)
{
//Validates user input
if (inputYears!= (termYear[i]))
{
out.println("Sorry, you entered an invalid option for the term of years: 7, 15 or 30. Please try again.");//Error Message to User
}
etc. . . .
```

Note that in this case the for loop does not declare a new local variable 'i', but it does initialize it to 0.

In summary, the root cause of the problem in the code you've posted is misplaced closing braces that result in empty for loops. This causes the for loop's control variable - a "local variable" to the for loop - to not be in scope at the lines following the empty for loop where it is needed.

If you are still confused, please come back and we'll use simpler examples to explain the concept of a variable's scope. Understanding the concept of scope is vital to your future programming success, and you should be more confident with it at this stage.

This post has been edited by GregBrannon: 30 June 2012 - 01:31 AM

### #11 carteyroazp

Reputation: -1
• Posts: 1
• Joined: 29-March 13

## Re: formula for mortgage calc. Numerator/Denominator with no values.

Posted 29 March 2013 - 08:01 AM