Leslie
Leslie

Reputation: 3644

use boolean value for loop

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);      
}

Upvotes: 2

Views: 11377

Answers (5)

Greg Bogumil
Greg Bogumil

Reputation: 1923

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);

Upvotes: -1

Bert F
Bert F

Reputation: 87533

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);
}

Upvotes: 0

thegrinner
thegrinner

Reputation: 12243

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.

Upvotes: 1

james
james

Reputation: 468

for (int i=0; i < (FYEProcessing ? 2 : 1); ++i){
   CreatePaymentRecords(TermDates, FYEProcessing);      
}

Upvotes: 7

matt b
matt b

Reputation: 139921

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);  
}

Upvotes: 7

Related Questions