Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
JavaScript loop ending early after special input?
let num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
while(isNaN(num_cap)) {
    alert("Input must be a number, try again.");
    num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
}
while(num_cap<=1) {
    alert("Number must be greater than 1, try again.");
    num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
}

I am new to programming, specifically javascript. I have written a higher-lower guess game and have resolved just about every issue I’ve come across in the code besides an issue where if my first while loop is triggered and again prompts the user for entry, If I then enter an input that should trigger the second while loop, it still passes through anyways. This problem doesn't happen if I simply begin with entering an input that triggers the second while loop without triggering the first. It only happens if I trigger the first while loop beforehand.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to check for both requirements (number is valid, and also larger than 1) at the same time.

let num_cap=parseInt((Math.round(prompt("Enter the highest number for your Higher-Lower game:"))));
while(isNaN(num_cap) || num_cap <= 1) {
    alert("Input must be a number larger than 1, try again.");
    num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
}

This is another example that I prefer because it does the parsing in once, in one place, also the validation check is simpler, just num_cap > 1:

let num_cap, isValid;
do {
    num_cap=parseInt((Math.round(prompt("Enter the max number:"))));
    isValid = num_cap > 1;
    if(isValid) { break; }
    alert("Input must be a number larger than 1, try again.");
} while(!isValid);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda