While error in joption pane: loop

Asked

Viewed 120 times

0

I’m having a serious problem with while in the following algorithm: You have a data set containing the height and gender (male, female) of 50 people. Make an algorithm that calculates and writes:

1 - the largest and smallest height of the group;

2 - the average height of women;

3 - number of men.


import javax.swing.JOptionPane;

public class Problema1122 {

    public static void main(String[] args) {

        float altura = 0, maiorAltura = 0, menorAltura = 0, mediaAlturaM = 0;
        int quantHomens = 0, quantMulheres = 0;
        String sexo = "";

        for (int i = 0; i < 5; i++) {
            **do {
                sexo = JOptionPane.showInputDialog("Digite o sexo da " + (i + 1) + " pessoa (F ou M): ");
            } while (!sexo.equalsIgnoreCase("f") || !sexo.equalsIgnoreCase("m"));**

            altura = Float.parseFloat(JOptionPane.showInputDialog("Digite a altura da " + (1 + i) + " pessoa: "));

            if (sexo == "f") {
                quantMulheres += 1;
                mediaAlturaM += altura;

            } else {
                quantHomens += 1;
            }
            if (menorAltura > altura || menorAltura == 0) {
                menorAltura = altura;
            } else if (maiorAltura < altura) {
                maiorAltura = altura;
            }

        }
        mediaAlturaM = mediaAlturaM / quantMulheres;

        JOptionPane.showMessageDialog(null,
                "A maior altura é: " + maiorAltura + "\n e a menor altura é: " + menorAltura
                        + ".\n A média de altura das mulheres é: " + mediaAlturaM + "\n e a quantidade de homens é: "
                        + quantHomens);
    }
}

I put the whole algorithm to have a general idea if necessary, but the problem is that when choosing sex, even putting F or M always keeps asking for the sex of the first person (loops in). I tried comparing string with ==, after I discovered that it should be use equals, I tried too, tried to change logic using | or ||...but nothing certain!!!

1 answer

0


Are you checking to see if

sexo difere de F ou sexo difere de M

Table tests:

true ou false  = true // Input = M
false ou true  = true // Input = F
true ou true = true //Input != F e M

That is why it is always on a loop. The correct logic would be:

sexo difere de F e sexo difere de M

Using the same table tests:

true e false = false // Input = M
false e true = false // Input = F
true ou true = true //Input != F e M

Browser other questions tagged

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