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

133
Visualizações
Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number : When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message

When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?

function askValue() {
    var answer = window.prompt(
    "Guess the number, enter a number between 1 and 10"
    );
    // keep the answer to use it in the loop
    if (!answer || isNaN(answer)) {
    console.log("Please enter a valid number");
    } else {
    return answer;
    }
}

function guessnumber() {
    var secret_number = Math.floor(Math.random() * 10) + 1;
    var guess = askValue();
    var attempts;
    var i = 0;
    var resultMessage = "You won, you take";
    while (win == false) {
    attempts++;
    if (guess < secret_number) {
        console.log("The secret number is bigger");
        i++;
    } else if (guess > Secret_number) {
        console.log("The secret number is smaller");
        i++;
    } else if (guess == secret_number) {
        win = true;
        if (i == 1) {
        var attempt_word = " ";
        attempt_word = "attempt";
        } else if ((attempt_word = "attempts")) {
        resultMessage += Number(i).toString() + attempt_word;
        }
    }
    console.log(resultMessage);
    }
}

// call the function
guessnumber();

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

0

I make your code works by fixing many mistake and bugs some of them:

  • using var which is old and it's better use the keyword let to declare variable!
  • checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
  • prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
  • many more... if you don't understand sth do a comment and I will explain to you!
    function askValue() {
        let answer = window.prompt(
        "Guess the number, enter a number between 1 and 10"
        );
        // keep the answer to use it in the loop
        if (!answer || isNaN(answer)) {
        alert("Please enter a valid number");
        } else if (+answer < 1 || +answer > 10) {
        alert("Please enter a number between 1 and 10");
        } else {
        return +answer;
        }
    }
    // Better using `let` than `var`
    function guessnumber() {
        let secret_number = Math.floor(Math.random() * 10) + 1;
        let guess = askValue();
        let attempts = 0; //initialse attempts with zero
        let i = 0;
        let resultMessage = "You won, you take ";
        let win = false; //declare win
        while (win == false) {
        attempts++;
        if (guess < secret_number) {
            alert("The secret number is bigger");
            i++;
            guess = askValue();
        } else if (guess > secret_number) {
            //s lowercase not capital
            alert("The secret number is smaller");
            i++;
            guess = askValue();
        } else if (guess == secret_number) {
            win = true;
            resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
            alert(resultMessage);
        } else {
            guess = askValue();
        }
        }
    }
    
    // call the function
    guessnumber();
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