What code do I put with the while?

Asked

Viewed 85 times

0

I want you to have a loop when typing the number for "yes": while(resp.equals(cont)) and while(!1.equals(cont)) .

import java.util.Scanner;
public class umm_whilezinho {

    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);

        int qtf = 0;
        int qtm = 0;
        String gen;
        int cont = 0;
        
        System.out.println("Qual o seu gênero? (Feminino ou masculino) ");
        gen = in.next();
        
        while(!1.equals(cont))  {
        if(gen == ("feminino")) {
            ++qtf;
        if(gen ==("Feminino"));
            ++qtf;
        if(gen == ("Masculino")) 
            ++qtm;
        if(gen == ("masculino")) 
            ++qtm;
        }
        System.out.println("Deseja adicionar mais uma pessoa? (Sim  =  1, Não = 2)");
        cont = in.nextInt();
        }
        
        System.out.println("Quantidade de mulheres: "+qtf);
        System.out.println("Quantidade de homens: "+qtm);
}
}

    

1 answer

3


Taking into account that the reading will be done at least once, you can place the code snippet that you want to repeat within a repeat structure while, with the condition while(cont == 1).

The condition you used didn’t work because the function equals is only used to compare a String with another, and the variable cont is of the whole type.

Also, comparisons made within the repeat to update the count variables do not need to be repeated. You can transform the string read in a word with all the lowercase characters (or all the lowercase characters, from any logic point of view) using the function toLowerCase. This eliminates the need for multiple comparisons. And comparisons were being made using the operator ==, in Java, as I said, strings must be compared using the function equals. The complete code gets:

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);

        int qtf = 0;
        int qtm = 0;
        String gen;
        int cont = 0;
        do
        {
          System.out.println("Qual o seu gênero? (Feminino ou masculino) ");
          gen = in.next();
          
          if(gen.toLowerCase().equals("feminino")) 
              ++qtf;
          if(gen.toLowerCase().equals("masculino")) 
              ++qtm;
          
            System.out.println("Deseja adicionar mais uma pessoa? (Sim  =  1, Não = 2)");
            cont = in.nextInt();
          
        }while(cont == 1);
        
        System.out.println("Quantidade de mulheres: "+qtf);
        System.out.println("Quantidade de homens: "+qtm);
}
}

See it working in repl.it (I changed the class name to Main, but just change it to the original name in your code)

  • 1

    now I understand, thank you very much!

Browser other questions tagged

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