Make loop if condition hurt

Asked

Viewed 63 times

0

I would like the user to be asked a message so that he or she enters a number, if this number is true, a screen will be displayed stating the number typed.

If the user type a letter, a message will be displayed stating that he has entered an invalid number and to type it again.

But I don’t know how to stay in loop until he enters a real number.

Below I leave my attempts.

var num1 = prompt('digite um numero');
if (isNaN(num1)) {
  document.write('numero invalido digite novamente')
}

I made the same code using functions, but I wonder if there’s another way.

Code using functions:

<!DOCTYPE html>
<html>

<body>
    <script>


        digite();

        var num1;
        function digite() {
            num1 = prompt('digite um numero');

         // caso usuario digite um numero inválido //
            if (isNaN(num1)) {
                alert('numero invalido digite novamente');
                digite();
            }
        }
        //caso usuário digite um numero válido //
        document.write("o numero digitado foi " + num1)
  </script>
</body>

</html>

2 answers

4


Just use a repeat loop. The logic is simple:

  • Before starting the loop, create a variable with the user’s initial response.
  • As long as the answer is incorrect, do the question again until it is correct.
  • Once the answer is correct, stop executing the repeat loop.

You can achieve this with a bow while:

function getResponse() {
  const data = prompt('Digite um número <= 5');

  // Adicione a lógica de validação aqui.
  if (parseInt(data) <= 5) {
    return data;
  }

  return false;
}

let resp = getResponse();

// Enquanto a resposta estiver inválida, execute o bloco de código.
while (resp === false) {
  alert('Tente de novo...');
  // Note que devemos atribuir à resposta uma outra "tentativa",
  // já que após cada iteração (incorreta), o usuário deve tentar novamente.
  resp = getResponse();
}

console.log('Resposta final:', resp);

But you can also do it using for, if you prefer. I just find it a little less intuitive:

function getResponse() {
  const data = prompt('Digite um número <= 5');

  // Adicione a lógica de validação aqui.
  if (parseInt(data) <= 5) {
    return data;
  }

  return false;
}

// Como precisamos de acessar a `resp` de fora do loop (após ele),
// não podemos declarar essa variável na declaração do `for`.
let resp = getResponse();

for (; !resp; resp = getResponse()) {
  alert('Tente de novo...');
}

console.log('Resposta final:', resp);

If you’re going to reuse this feature, you can even create a function wrapper:

function getResponse({ getter, validator, onError, onSuccess }) {
  let resp = getter();
  let isValid = validator(resp);

  while (!isValid) {
    onError(resp);

    // "Rodar" novamente:
    resp = getter();
    isValid = validator(resp);
  }

  onSuccess(resp);
}

getResponse({
  getter: () => prompt('Digite um número menor ou igual a 5.'),
  validator: (resp) => parseInt(resp) <= 5,
  onError: (resp) => alert(`O valor "${resp}" não é válido.`),
  onSuccess: (resp) => alert(`Acertou! O número ${resp} é válido!`)
});

  • Thank you. I had doubts about that. I’m glad I found this question.

1

A simple form, also using while and a function verifica which returns an object with two data:

function verifica(n){
   return { num: n, isan: !isNaN(n) };
             ↑       ↑
       caractere    verifica se é um número: 'true' se for número
        digitado
}

The while:

var ver;
while(!ver){
   var num1 = verifica(prompt('digite um numero'));
   var vnum = num1.num || '';
   ver = vnum.trim().length ? num1.isan : 0;
   !ver ? alert('numero invalido digite novamente') : num1 = vnum;
}

Declares the variable ver initially worthless (false), and as long as she is false the while will rotate.

The variable num1 receives the function return object.

The variable vnum will be the value of the key num of the function return object or will be an empty string ('') if the user tries to cancel or close the prompt.

The value of ver will change according to function return: if what was typed in the prompt has at least 1 character, the value of ver will be the value of the key isan of the returned function object, otherwise it will be equal to 0, that is false.

With that, on the last line of while, if ver for false (!ver) will trigger the alert and continue to run while, if not, it will change the value of the variable num1 for what was typed at the prompt, quit while (because !ver is no longer false) and print the result on the screen (document.write).

Behold:

function verifica(n){
   return { num: n, isan: !isNaN(n) };
}

var ver;
while(!ver){
   var num1 = verifica(prompt('digite um numero'));
   var vnum = num1.num || '';
   ver = vnum.trim().length ? num1.isan : 0;
   !ver ? alert('numero invalido digite novamente') : num1 = vnum;
}
document.write("o numero digitado foi " + num1);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.