Error when trying to use conditional structure equality in java

Asked

Viewed 19 times

0

The code below is giving error in line if (sexo = 1){, can anyone explain to me why?

int sexo = 0, sexoF = 0, sexoM = 0, bom = 0, ruim = 0;

while (sexo != -1){

    System.out.println("Digite o sexo: ");

    System.out.println("[1] Homem");

    System.out.println("[2] Mulher");

    System.out.println("Digite -1 para sair")

    if (sexo = 1){ 
        ++sexoM;
    } else {
        ++sexoF;
  • sexo = 1 is setting the value 1 in the variable. To compare, use sexo == 1

  • thank you very much! you know why the loop doesn’t stop when I type -1 on the run?

  • Because you are only printing messages. To get data that is typed, you need to use something that reads this data (look for java.util.Scanner, should already have several examples on the site). After you need to test if what was typed is -1 and use break to get out of the loop

  • Thanks man, I get it, I solved it here.

No answers

Browser other questions tagged

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