0

I have been trying to practice JavaScript after awhile withou using it. I am doing a simple voting exercise where users use numbers 1,2 or 3 in a window.prompt or a different number to finish the voting. Problem is, I have used a "do while" to create the loop and the browser doesn't seem to read it. It skips directly to the last "alert". What should I do? Code follows:

let end = false;

let votosFulano = 0;
let votosCicrano = 0;
let votosBeltrano = 0;

let mostVoted = "no votes yet";

do {
  let voto = window.prompt("Vote 1 for Fulano, 2 for Cicrano and 3 for Beltrano ou outro número para encerrar a votação");

  if (voto == 1) {
    votosFulano += 1;
    end = false;
  }

  if (voto == 2) {
    votosCicrano += 1;
    end = false;
  }

  if (voto == 3) {
    votosBeltrano += 1;
    end = false;

  }

  if (voto !== 1 && voto !== 2 && voto !== 3) {
    if (votosFulano > votosBeltrano && votosFulano > votosCicrano) {
      mostVoted = "Fulano";
    } else if (votosBeltrano > votosFulano && votosBeltrano > votosCicrano) {
      mostVoted = "Beltrano";
    } else if (votosCicrano > votosFulano && votosCicrano > votosBeltrano) {
      mostVoted = "Cicrano";
    }

    end = true;
  }
} while (end == false);

if (votosFulano == 0 && votosCicrano == 0 && votosBeltrano == 0) {
  alert("No votes");
} else {
  alert("Winner is " + mostVoted);
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 2
    What do you mean by "*the browser doesn't seem to read it. It skips directly to the last "alert"*"? What *should* be happening and what happens instead? When I run the code, I get no errors and nothing seems to be skipped, either. – VLAZ Dec 01 '21 at 19:39
  • When I run it on Chrome, the first window opens asking me for the vote number. No matter what number I type, it always shows the same final alert with the "mostVoted" variable unchanged, it doesn't wait for any other votes nor does it count the first one. It should only end the "do while" if the input from user was different than 1 ,2 or 3. – Adjardo Lobo Dec 01 '21 at 19:45
  • 1
    OK, I see. `voto !== 1` is strict inequality and `prompt` gives you a string. So `"1" !== 1` is `true` because they are of different types. Use loose inequality (like you use loose equality in the previous `if` statements) or convert the result of `prompt` to number. – VLAZ Dec 01 '21 at 19:49
  • Thanks! Just correct it and it is now working. – Adjardo Lobo Dec 01 '21 at 19:58

0 Answers0