Home > Enterprise >  The last "else if" cannot works. How can I do it?
The last "else if" cannot works. How can I do it?

Time:08-02

Cannot execute the last "if else". Only the first 2 are considered. How can I trigger the last one?

let i;
for (i = 1; i < 19; i  ) {
  if (i % 3 === 0) {
    console.log("three");
  } else if (i % 5 === 0) {
    console.log("five");
  } else if (i % 3 === 0 && i % 5 === 0) {
    console.log("both");
  } else {
    console.log(i);
  }
}

CodePudding user response:

Your logic is wrong. if one of these is true i % 3 === 0 i % 5 === 0 then the i % 3 === 0 && i % 5 === 0 statement will not execute.

So change like this.

let i;
for (i = 1; i < 19; i  ) {
  if (i % 3 === 0 && i % 5 === 0){
    console.log("both");
  }
  else if (i % 3 === 0) {
    console.log("three");
  } else if (i % 5 === 0) {
    console.log("five");
  }    
  else {
    console.log(i);
  }
}

CodePudding user response:

Your code has different states:

Either it is divisible by 3, 5 or 15 or none.

A number which is divisible by 15, is divisible by 3 or 5 too.

So your third condition will never occur because the first or second one is true.

You have to put this if (i % 3 === 0 && i % 5 === 0) condition as your first one.

CodePudding user response:

According to the code you wrote, the common multiple of 3 and 5 has already ended in the 1st, 2nd if statement. So by changing the order, the logic that contains 3 and 5 at the same time operates first.

let i;
for (i = 1; i < 19; i  ) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log("both");
  } else if (i % 3 === 0) {
    console.log("three");
  } else if (i % 5 === 0) {
    console.log("five");
  } else {
    console.log(i);
  }
}

  • Related