ParaChase
ParaChase

Reputation: 319

Why is this giving me an infinite loop?

I was going through a code used to calculate investments until it has doubled and I received an infinite loop that I can't seem to solve. Can anyone figure out why this is giving me an infinite loop? I've gone through myself but I can't seem to find the problem. The "period" referred is how many times per year the interest is compounded.

double account = 0; //declares the variables to be used
   double base = 0;
   double interest = 0;
   double rate = 0;
   double result = 0;
   double times = 0;
   int years = 0;
   int j;

   System.out.println("This is a program that calculates interest.");
   Scanner kbReader = new Scanner(System.in); //enters in all data  
   System.out.print("Enter account balance: ");
   account = kbReader.nextDouble();
   System.out.print("Enter interest rate (as decimal): ");
   rate = kbReader.nextDouble();

   System.out.println("                    " + "Years to double" + "     " +     "Ending balance");
   base = account;
   result = account;
   for (j=0; j<3; j++){
       System.out.print("Enter period: ");
       times = kbReader.nextDouble();
       while (account < base*2){
           interest = account * rate / times;
           account = interest + base;
           years++;
       }
        account = (((int)(account * 100))/100.0);
       //results
       System.out.print("                         " + i + "               " + account + "\n");
       account = result;
   }

The code should ask for three "periods", or three different times the entered data is compounded per year (ex annually, monthly, daily etc.)

Thanks a lot!

Upvotes: 0

Views: 145

Answers (3)

Sameer
Sameer

Reputation: 4389

Instead of doing

account =interest +base

You should have

account = interest +account

Upvotes: 1

CrazyCasta
CrazyCasta

Reputation: 28362

You should add some sanity checking. Either check if all the numbers will result in a finite number of loops (account and rate != 0, maybe some other stuff), or more simply, break if you've looped more times than would be reasonable (say 1000 for instance). My guess is that rate is 0 resulting in no increase in account, therefore it will loop forever.

You have a calculation error:

account = interest + base;

Presumably this should be:

account = account + interest;

Also, are you sure you want to have the int cast?

account = (((int)(account * 100))/100.0);

You're throwing away the values smaller than 1 cent apparently. However, if the interest is too small you will not get any change.

Upvotes: 1

Bohemian
Bohemian

Reputation: 425358

The reason it may loop forever is that the double calculation of account is effectively truncated by casting to int, so it may never change if rate is too small and the new value of account isn't made larger by at least 0.005.

Upvotes: 0

Related Questions