Home > Enterprise >  if statement producing 2 unintended outcomes
if statement producing 2 unintended outcomes

Time:01-06

                                if (localCounter < 4) {
                                  localCounter  ;
                                }
                                if (localCounter < 4) {
                                  globalCounter  ;
                                }

I have 2 int variables that are set to 0 that increase when a button is pressed. here is the if statements taken from the setstate.

The problem i'm having with these statements is that the localCounter reaches 4 but the globalCounter stops at 3.

I've also tried the below statement but then the global counter doesn't stop going up

                             if (localCounter <= 4) {
                                  globalCounter  ;
                                }

does anyone know why the local counter stops at 4 but the global counter only stops at 3? and how i could rewrite it to fix this please?

thanks so much for your help

CodePudding user response:

Your second condition wrong because localCounter always equals to 4 and globalCounter increments for each time. Try to combine increments by this way:

if (localCounter < 4) {
  localCounter  ;
  globalCounter  ;
}

CodePudding user response:

Of course global counter will stop at 3, because when localCounter = 3 and globalCounter = 3, in the first if, localCounter < 4 is true, so localCounter will increment to 4, in this case the seconde if will be false. so globalCounter will never reach 4. so the best solution is by combine the two increments in same if

if (localCounter < 4) {
  globalCounter  ;
  localCounter  ;
}

CodePudding user response:

in second if statement you are checking against localCounter instead of globalCounter.

you may also consider this:

if (localCounter < 4 ) {
  localCounter  ;
  globalCounter  ; 
}
  • Related