Program enters infinite loop

Asked

Viewed 112 times

4

My goal with the code was to put together a game that asked the person what number the computer would be "thinking" (from 1 to 100), and as the person said a number from 1 to 100, the computer said if the generated random number is larger or smaller than what the person typed until they were right.

However, when I run the program, it loops in with "Guess the number".

    Random rand = new Random();
    int numSorte = rand.nextInt(100) + 1;

    System.out.println("Adivinhe o número que estou pensando,ele está entre 1 e 100");

    boolean continuar = true;

    Scanner scan = new Scanner(System.in);

    while(continuar = true) {
        System.out.println("Adivinhe o número :");
    }
    int numUsuario = Integer.valueOf(scan.next());

    if(numUsuario == numSorte) {
        System.out.println("VOCÊ GANHOU!!!!!!");
        continuar = false;
    }
    else if(numUsuario < numSorte) {
        System.out.println("O número" + numUsuario + "é menor do que o número sorteado");
    }
    else {
        System.out.println("O número" + numUsuario + "é maior do que o número sorteado");
    }
    scan.close();
  • You closed while with just this text in an infinite loop, so. Move the key just below the System.out.println("Adivinhe o número :"); to just above the scan.close() that will run correctly

  • Damn, man, thank you very much,.

  • Okay, I’m new here I don’t know how it works,

  • I forgot to mention the other question from the PA: in addition to accepting the answer, you can vote +1 on it.

1 answer

5


You closed the while with just the System.out.println("Adivinhe o número :"); in an infinite loop, for that reason does not come out of that run.

Move the key just below the System.out.println("Adivinhe o número :"); to just above the scan.close(), so as to involve all the rest of the code within the loop that will run correctly:

Random rand = new Random();
int numSorte = rand.nextInt(100) + 1;

System.out.println("Adivinhe o número que estou pensando,ele está entre 1 e 100");

boolean continuar = true;

Scanner scan = new Scanner(System.in);

while(continuar = true) {

        System.out.println("Adivinhe o número :");

    int numUsuario = Integer.valueOf(scan.next());

    if(numUsuario == numSorte) {
        System.out.println("VOCÊ GANHOU!!!!!!");
        continuar = false;
    }
    else if(numUsuario < numSorte) {
        System.out.println("O número" + numUsuario + "é menor do que o número sorteado");
    }
    else {
        System.out.println("O número" + numUsuario + "é maior do que o número sorteado");
    }
    scan.close();
}

Browser other questions tagged

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