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

147
Visualizações
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 Respostas
Responde à pergunta

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 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