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

149
Vistas
Show message "no score entered" if user inputs a specific number into a prompt

Currently my JSFiddle allows a user to input some exam scores one number at a time and shows the average and total score for the numbers they give. Currently, if they enter -999 into the box, it means they are finished entering numbers and the average and total can be calculated.

How can I edit this to make it so that if the user entered -999 as their first input it displays “No score entered.”?

<script>

function userInput() {

  var examScores = 0;
  var totScores = 0;
  var i = 0;
  var scores = [];

  while (true) {
    examScores = parseInt(prompt("Enter a score or enter -999 when you're finished: "));

    if (examScores === -999 && scores.length === 0) {
      document.getElementById("scores").innerHTML = "No score entered.";
      break;
    }

    else if (examScores === -999) {
      break;
    }

    else {
      scores.push(examScores);
      i++;
    }
  }

  for(var i = 0; i < scores.length; i++) {
    totScores = totScores + scores[i];
  }

  document.getElementById("scores").innerHTML = "<h1> The sum of these scores is: "+totScores.toFixed(2)+"<br/> The average of these scores is: "+(totScores/scores.length).toFixed(2);
}

</script>

<h1>Exam Scores</h1>
<h3>Click to enter scores</h3>
<input type="button" value="Enter student scores" onclick="userInput()" />
<div id="scores"></div>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to return instead of just breaking the loop.

if (examScores === -999 && scores.length === 0) {
  document.getElementById("scores").innerHTML = "No score entered.";
  return;
}

Breaking the loop solely will cause the function execution to continue, hence always reaching

document.getElementById("scores").innerHTML = "<h1> The sum of these scores is: "+totScores.toFixed(2)+"<br/> The average of these scores is: "+(totScores/scores.length).toFixed(2);

Since the above line is being executed, your own work will be overwritten. Returning from within the loop would end the execution of the function.

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