loops

I am trying to print the payment schedule for my mortgage program. I have the variable balance declared at the top, however the compiler is saying 'MortgageCalculatorDisplay.java:46: variable balance might not have been initialized'. Do i have something else wrong in the code? thanks


/*class MortgageCalculator*/
import java.io.*;
import java.text.DecimalFormat;

class MortgageCalculatorDisplayT
{

public static void main(String arguments[])
       {

/*Declaring Program Variables*/
double I = 0.0575;//*Interest rate
double P = 200000.00;//*Amount of Loant
double J = I/12; //*Monthy interest
int N = 360; //* 30 yrs -12 months each year is 360 months
double balance;
double monthlyInterest;
double monthlyPrincipal;
DecimalFormat df = new DecimalFormat("$#,###.00");
// Create new Decimal Format object that has the format required for this program

//calculate monthly payment
//Mortgage Formula for code is M=P*(J/(1-(1+j)**-N))
//P= principal amount of loan
//J= monthly interest in decimal form
//N= number of months
double mortgage = (Math.pow((1 + J), N) -1) / (J * Math.pow((1 + J), N));
double payment = P / mortgage; //*Rate Calculation


/*Output*/
//System.out.println (" The monthly mortgage payment is $" + df.format(payment));

// format column headers for results to be displayed

System.out.println("\n\nPayment\tPrincipal\t\tInterest\t\tBalance");
System.out.println("---------\t---------\t---------\t---------");

int lines = 0;

for(int i=0; i<N; i++)
            {
// information to display
System.out.println((i+1) + "\t\t" + df.format(P) +
"\t\t" + df.format(J) +
"\t\t" + df.format(balance));

// calculate interest and principal payments
monthlyInterest = (balance * J);
monthlyPrincipal = (payment - monthlyInterest);

//reduce balance
balance -= monthlyPrincipal;

// pause every 25 lines
if(lines == 25)
            {
            lines = 0;

try
       {
Thread.sleep(1000);
      }
catch (InterruptedException e)
{

      }
            }
else
{
lines++;
}

      }

}
}
pgmtklAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mick BarryJava DeveloperCommented:
> double balance;

change that to:

double balance = 0.0;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
pgmtklAuthor Commented:
It compiles after i add the 0.0, however when i run the program i get the following 'Exception in thread "main" .
  .'
Tommy BraasCommented:
What exception is that?
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

pgmtklAuthor Commented:
for the following program:

/*class MortgageCalculator*/
import java.io.*;
import java.text.DecimalFormat;

class MortgageCalculatorDisplayT
{

public static void main(String arguments[])
       {

/*Declaring Program Variables*/
double I = 0.0575;//*Interest rate
double P = 200000.00;//*Amount of Loant
double J = I/12; //*Monthy interest
int N = 360; //* 30 yrs -12 months each year is 360 months
double balance = 0.0;
double monthlyInterest;
double monthlyPrincipal;
DecimalFormat df = new DecimalFormat("$#,###.00");
// Create new Decimal Format object that has the format required for this program

//calculate monthly payment
//Mortgage Formula for code is M=P*(J/(1-(1+j)**-N))
//P= principal amount of loan
//J= monthly interest in decimal form
//N= number of months
double mortgage = (Math.pow((1 + J), N) -1) / (J * Math.pow((1 + J), N));
double payment = P / mortgage; //*Rate Calculation


/*Output*/
//System.out.println (" The monthly mortgage payment is $" + df.format(payment));

// format column headers for results to be displayed

System.out.println("\n\nPayment\tPrincipal\t\tInterest\t\tBalance");
System.out.println("---------\t---------\t---------\t---------");

int lines = 0;

for(int i=0; i<N; i++)
            {
// information to display
System.out.println((i+1) + "\t\t" + df.format(P) +
"\t\t" + df.format(J) +
"\t\t" + df.format(balance));

// calculate interest and principal payments
monthlyInterest = (balance * J);
monthlyPrincipal = (payment - monthlyInterest);

//reduce balance
balance -= monthlyPrincipal;

// pause every 25 lines
if(lines == 25)
            {
            lines = 0;

try
       {
Thread.sleep(1000);
      }
catch (InterruptedException e)
{

      }
            }
else
{
lines++;
}

      }

}
}
Tommy BraasCommented:
Works fine for me.
Tommy BraasCommented:
I should say that it works fine for me to run the program without runtime errors. There seems to be a problem with your calculations, but that's another matter.
pgmtklAuthor Commented:
It compiles but i still  get this error when i run it. "
java.lang.NoClassDefFoundError: MortgageCalculatorDisplay
Exception in thread "main"
 Do i need to import a different class? Thx
Tommy BraasCommented:
Ensure that the name of the class MortgageCalculatorDisplayT matches that of your file. In this case, I think you've misnamed the class. Change MortgageCalculatorDisplayT to MortgageCalculatorDisplay.
pgmtklAuthor Commented:
That worked thanks. I just realised it is showing the principal amount, then all $0 in interest and then the accumulation of the principal paid instead of the balance. i have the calculations coded but they are not working in order. Do i need to rearrange them? or am i missing a variable? Sorry, new to this.thanks
Mick BarryJava DeveloperCommented:
> double J = I/12; //*Monthy interest

try changing that to:

double J = I/12.0; //*Monthy interest
pgmtklAuthor Commented:
i tried changing the double j variable to 12.0. it seems it still is calculatin the $0.
i have this to calculate, do i need to change that interest??

// calculate interest and principal payments
monthlyInterest = (balance * J);
monthlyPrincipal = (payment - monthlyInterest);

//reduce balance
balance -= monthlyPrincipal;

Tommy BraasCommented:
>> try changing that to:
>> double J = I/12.0; //*Monthy interest
Won't help as I is a double already, which means that the int 12 is promoted to a double.

The calculation is not working correctly. Is this for a fixed monthly payment type of mortgage?
pgmtklAuthor Commented:
yes it is a monthly payment mortgage for 360 months. it should show the payment, interest and balance on each line.
Tommy BraasCommented:
Right, so the question was whether this type of loan has a fixed monthly payment or not. Fixed monthly payment is what is used on annuity loans, i.e. same amount every month.
Tommy BraasCommented:
The following code will deal correctly with the case of a variable monthly payment:

      public static void main(String arguments[]) {
            /*Declaring Program Variables*/
            double annualInterestRate = 0.0575;//*Interest rate
            double principal = 200000.00;//*Amount of Loant
            double monthlyInterestRate = annualInterestRate/12; //*Monthy interest
            int periods = 360; //* 30 yrs -12 months each year is 360 months
            double balance = principal;
            double monthlyInterest;
            double monthlyPrincipal;
            DecimalFormat df = new DecimalFormat("$#,###.00");
            System.out.println("\n\nPayment\t\tBalance\t\tInterest\t\tAmortization\t\tPayment amount");
            System.out.println("---------\t---------\t---------\t---------\t---------");
            
            int lines = 0;
            
            for(int i=0; i < periods; i++) {
                  double interestPayment = balance * monthlyInterestRate;
                  double amortization = principal / periods;
                  double payment = interestPayment + amortization;

                  // information to display
                  System.out.println((i+1) + "\t\t\t" + df.format(balance) +
                                                       "\t\t" + df.format(interestPayment) +
                                                       "\t\t" + df.format(amortization) +
                                                       "\t\t" + df.format(payment));
                                    
                  //reduce balance
                  balance -= amortization;
                  
                  // pause every 25 lines
                  if(lines == 25) {
                        lines = 0;
                        try { Thread.sleep(1000); } catch (InterruptedException e) {}
                  } else {
                        lines++;
                  }
            }
      }
pgmtklAuthor Commented:
Thanks. that worked perfect. Thanks for all the help
Tommy BraasCommented:
>> pgmtkl
Eerrh, so you take my solution and give objects the credit (and points) for something that doesn't work?!?!?
Tommy BraasCommented:
I suggest you ask support to re-open the question and redistribute the points.
pgmtklAuthor Commented:
Support can you re-open the question?
I am sorry, I am new to using this site. I have only had a few posts. I did not know that you could select which one to grade, i thought it was the entire post I responded to. I am so sorry. If they can re-open, i can adjust.
Tommy BraasCommented:
No worries. You need to click on the Support link at the top of the page, and ask a question there.
Tommy BraasCommented:
;-D
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.