mardi 14 novembre 2017

Java - How to read more than one if statement using && [duplicate]

This question already has an answer here:

I am creating this code that has to return the oldest age and the percentage of women between the ages of 18 and 35 on the total population, my code is at follows:

public static void main(String[] args){

    int age,highestAge=-1,femHab = 0;
    double totalHab=0,percentage;

    String sex;


    JOptionPane.showMessageDialog(null, "Type the habitant's age or type -1 to finish: ");

    age = Integer.parseInt(JOptionPane.showInputDialog("Type the habitant's age: "));

    while(age != -1){
        sexo = JOptionPane.showInputDialog("Type the habitant's sex: M or F.");

            if(age>highestAge){
                highestAge = age;
            }
        totalHab = totalHab + 1;

        if(age>= 18 && age<=35 && sex=="F"){
            femHab = femHab + 1;
            }


        age = Integer.parseInt(JOptionPane.showInputDialog("Type the age of the next habitant or type -1 to finish: "));                    
    }

    if(totalHab>0){
        percentage = femHab*100/totalHab;
        JOptionPane.showMessageDialog(null, "The total of habitants is: "+totalHab+".");
        JOptionPane.showMessageDialog(null, "The number of women is: "+femHab+".");
        JOptionPane.showMessageDialog(null, "The highest age is: "+highestAge+" .");
        JOptionPane.showMessageDialog(null, "A percentage of women is: "+percentage+"%.");
    }


}

But when I run this and put some values in, it only shows the total number of people and the highest age, but the female population and percentage stays at 0. How do I fix the problem to correctly show the total number and percentage of women?

Aucun commentaire:

Enregistrer un commentaire