tags:

views:

179

answers:

5

So technically a boolean is True (1) or False(0)...how can I use a boolean in a loop?

so if FYEProcessing is False, run this loop one time, if FYEProcessing is true, run it twice:

for (Integer i=0; i<FYEProcessing; ++i){
   CreatePaymentRecords(TermDates, FYEProcessing);      
}
+7  A: 

So technically a boolean is True (1) or False(0)

This is not true in Java. You cannot use an integer in place of a boolean expression in a conditional, i.e. if (1) {...} is not legal.

You are better of just doing this sequentially rather than attempting to use some sort of looping strategy to avoid having two lines which call CreatePaymentRecords()

CreatePaymentRecords(TermDates, FYEProcessing);  
if (FYEProcessing) {
    //run again
    CreatePaymentRecords(TermDates, FYEProcessing);  
}
matt b
thanks, that will work...with a little modification, I need the createPaymentRecords to enter a 0 the first time and a 1 the second time, so I'd have to hard code the values...
Leslie
A: 

if you simply want to execute this as long as the boolean is a particular value then use a do or while loop.

do { CreatePaymentRecords(TermDate, FYEProcessing); } while (FYEProcessing);
gbogumil
Unless CreatePaymentRecords updates the value of FYEProcessing (which we have not been told), then this loop will never exit.
Mike Clark
given the question "how can I use a boolean in a loop?" my answer is informative. Perhaps the author does know about do or while loops. Using the if statement posted is not code most people would like to debug.
gbogumil
+7  A: 
for (int i=0; i < (FYEProcessing ? 2 : 1); ++i){
   CreatePaymentRecords(TermDates, FYEProcessing);      
}
james
A: 

For a loop that would use a boolean true/false for the condition, just use do {...} while (condition) or while (condition) {...}. The first will always run at least once, then check the condition. The second would run only if the condition was initially true.

thegrinner
A: 

I think we should strive to make code clearly understandable and I have hard time thinking where "boolean loop" is clear. Trying to use a "boolean loop" may seem slicker in code, but I think it detracts from the understandability and maintainability of the code.

I distilled what you described:

so if FYEProcessing is False, run this loop one time, if FYEProcessing is true, run it twice

into

so if FYEProcessing is False, run this loop one time [with false], if FYEProcessing is true, run it twice [with false, then true]

or

run this loop one time with false. If FYEProcessing is true, run it again with true

CreatePaymentRecords(TermDates, false);
if (FYEProcessing) {
    CreatePaymentRecords(TermDates, true);
}
Bert F