Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda