Search code examples
javawhile-loopinteger-division

How come my program freezes up when I click calculate?


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.


Solution

  • 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.