steven
steven

Reputation: 698

For Loop Assistance

So my for loop causes a crash and I know exactly why, but I'm unsure of a way to rewrite this to get it to do what I'm trying to accomplish.

I'm trying to get it to take out money from a compounding interest each day and total it up for the month (which is set for ever 30 days). The user inputs the number of days they are trying to calculate for. So what is causing the crash is if they put in anything other than something divisible by 30.

I'm having difficulty coming up with a way to rewrite this and could use any suggestions. I would like it to do something if they put in 65 it calculates 2 months worth and then display like insuficiant days for month 3. Any help is always greatly appreciated. Thanks in advance.

for (int i = 0; i < numDays; i+=30){
    double cash=0;
    for (int n=1; n < 30; n++){
        int currentDay;
        currentDay= n+i;
        cash=cash+dailyMoney[currentDay];
    }
    month++;
    if(monthlyChecks == null)
        monthlyChecks = "\nCheck on month "+month+": $"+df.format(cash)+"\n";
    else 
        monthlyChecks = monthlyChecks+"\nCheck on month "+month+": $"+df.format(cash)+"\n";
}

numDays is the user inputted number of days.... monthlyChecks is a String.... dailyMoney[] is the array that holds the amount for each day.

Upvotes: 0

Views: 110

Answers (2)

sparc_spread
sparc_spread

Reputation: 10833

Given that user is required to enter days, maybe something like

int numMonths = numDays / 30;
int remainder = numDays % 30;

System.out.println ("Calculating for " + numMonths + " months");

if ( remainder != 0 ) {
    numDays -= remainder;
    System.err.println ("Insufficient days for month " + (numMonths + 1));
}

This should all be placed before the rest of your code, including (and especially) before the dailyMoney = new double[numDays] part.

Upvotes: 1

Jonathan
Jonathan

Reputation: 945

Okay, sounds to me like what you are trying to do with your "insufficient days for month 3" is this: (Assuming numDays is an int)

numMonths = numDays / 30 //If numDays is an int, this will round down.
extraDays = numDays % 30

for (int i = 0; i < numMonths; i+=30){
   double cash=0;
   for (int n=1; n < 30; n++){
      int currentDay;
      currentDay= n+i;

      cash=cash+dailyMoney[currentDay];
   }
   month++;
   if(monthlyChecks == null)
      monthlyChecks = "\nCheck on month "+month+": $"+df.format(cash)+"\n";
   else 
      monthlyChecks = monthlyChecks+"\nCheck on month "+month+": $"+df.format(cash)+"\n";
   }
}

//Then at some point
Systme.out.println("Insuffiecent days for " + numMonth + 1 " months. " + 30 - extraDays " days short).")

Upvotes: 1

Related Questions