-1

Here is my code:

private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                             
    int intInitialInvest = Integer.parseInt(this.txtInputInitialInvest.getText());
    int intAnnualInterest = Integer.parseInt(this.txtInputAnnualInterest.getText());
    int intEndingValue = Integer.parseInt(this.txtInputEndingValue.getText());                
    double dblAnnualPercent = intAnnualInterest/100;

    int count = 0;
    while (intInitialInvest < intEndingValue){
        intInitialInvest += (intInitialInvest * dblAnnualPercent);
        count += 1;
    }
    this.lblOutputYears.setText("The number of years required is " + count);
}                               

This program is supposed to calculate how many years (which is count) it takes for example for a cd with a value of $2000 to become $5000 with an annual interest rate of 8%. This should then return 12. What I did was create a while loop which runs until the $2000 turn into $5000 or more from interest which is expressed by intInitialinvest += (intInitialInvest * dblAnnualPercent);

Every time I run the program by clicking the "Calculate" button, the program freezes and doesn't do anything then I have to go into task manager to close it.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109

2 Answers2

0

If intInitialInvest=0 or dblAnnualPercent=0 and intEndingValue > 0 you'll loop forever.

while (intInitialInvest < intEndingValue){
    intInitialInvest += (intInitialInvest * dblAnnualPercent);
    count += 1;
}

You have to test your values before you enter the loop, especially as you seem to read these values from some input. This is a possible attack vector, even when you assert on these values, as your algorithm breaks, when someone feeds input that makes intInitialInvest=0 or intAnnualInterest<100.

ikrabbe
  • 1,909
  • 12
  • 25
0

Be careful with integer divisions:

double dblAnnualPercent = intAnnualInterest/100;

causes the value of dblAnnualPercent to be 0.0, and thus you run into an infinite loop. You perform an integer division (e.g 8/100=0) then convert to double (0.0, not 0.05 as you would have expected).

double dblAnnualPercent = intAnnualInterest/100.;

should fix your bug.

Hint: add assertions, run your problem with assertions enabled.

assert(dblAnnualPercent > 0.);

would have saved you (assuming you run your program with -ea).

But also try to solve your problem without a loop. There is a closed form solution to your problem, using math instead of loops... that solution is one line only.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194