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

179
Visualizações
How do i access a variable inside a while loop?

I am trying to access question 2 in the the second while loop, but i can't since it is in a block scope in the first while loop. I tired declaring it outside of the while loop but then the while loop will not work. Any help is appreciated. The if statement in the second while loop will not work because question 2 is in a block scope.

var readlineSync = require("readline-sync");

function run() {
  var question1 = readlineSync.question("Press any key to start the game");

  const randomNumber1 = Math.floor(Math.random() * 3) + 1;
  const randomNumber2 = Math.floor(Math.random() * 3) + 1;

  /*first placement*/
  firststring(1);
  function firststring(stringlength) {
    var emptyString1 = "";
    var emptyString2 = "";
    var characters = "ABC";
    var characters2 = "ABC";
    let operation1 = false;
    let operation2 = false;

    for (var i, i = 0; i < stringlength; i++) {
      emptyString1 += characters.charAt(
        Math.floor(Math.random() * characters.length)
      );
    }
    for (var i, i = 0; i < stringlength; i++) {
      emptyString2 += characters.charAt(
        Math.floor(Math.random() * characters2.length)
      );
    }
    var totalOne = emptyString1 + randomNumber1;
    var totalTwo = emptyString2 + randomNumber2;
    var toString1 = totalOne.toString();
    var toString2 = totalTwo.toString();
    console.log(toString1);
    console.log(toString2);

    if (toString1 === toString2 || totalOne === totalTwo) {
      run();
    }

    let question2;

    while (!operation1) {
      question2 = readlineSync.question('Enter a location to strike ie "A2"');

      if (question2 === toString1 || question2 === toString2) {
        operation1 = true;
        console.log("Hit. You have sunk a battleship. 1 ship remaining.");

        break;
      } else {
        console.log("You have missed!");
      }
    }

    let question3;
    let question4;


    while (!operation2) {
      question3 = readlineSync.question("Enter a location to strike the second battleship")

        if (question3 === toString1 || question3 === toString2) {
          operation2= true;
          console.log('HIT!')
           break;
        } else {
          console.log('You have misssed')
        }


        if (question3 === question2) {
          console.log("You have already entered that value.");
        }
      }
      
              question4 = readlineSync.question(
                "You have destroyed all battleships. Would you like to play again? Y/N"
              );
          
      
      
            if(question4 === "Y" || question4 === "y") {
              run();
            }
    }

}
run();

enter image description here

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

0

In the code above, question2 is declared and available for the whole firststring function, that and is available to both while loops.

let in JavaScript defines a variable for its current scope and anything below like so:

let a;
let b = 3;
if (true) {
  console.log(b); // 3
  let c = 5;
  b = 4;
  a = 6;
}
console.log(a); // 6
console.log(b); // 4
// console.log(c); // Uncaught ReferenceError: c is not defined

EDIT: With the example result provided, the problem is that the if (question3 === question2) check is called after the "hit check" (which breaks the loop). You need this:

while (!operation2) {
  question3 = readlineSync.question("Enter a location to strike the second battleship")
  if (question3 === question2) {
    console.log("You have already entered that value.");
  } else if (question3 === toString1 || question3 === toString2) {
    operation2= true;
    console.log('HIT!')
    break;
  } else {
    console.log('You have misssed')
  }
}
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