Nicolas Segarra Nicolas Segarra - 3 months ago 6
Java Question

What should I do to count how many females or males are there in my Person class?

I created a class with 3 persons on it, and inside it is a function named showSexDistribution that counts how many males and females are there, but I don't know what to do

package test;

import java.util.Scanner;

public class Person {
private static int maleCount;
private static int femaleCount;
private String name;
private char sex;
private int age;

public int getAge()
{
return age;
}

public void setAge(int a)
{
age=a;
}

public String getName()
{
return name;
}

public void setName(String n)
{
name=n;
}

public char getSex()
{
return sex;
}

public void setSex(char s)
{
sex=s;
}

public void ShowSexDistribution()
{
maleCount = 0;
femaleCount = 0;
}

public void tellSex()
{
System.out.println("\nName:"+name);
getName();
System.out.println("Sex:"+sex);
getSex();
}

public void tellAge()
{
System.out.println("Age:"+age);
getAge();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1= new Person();
Person p2= new Person();
Person p3= new Person();

p1.setName("Vincent");
p1.setSex('M');
p1.setAge(20);

p2.setName("Janice");
p2.setSex('F');
p2.setAge(36);

p3.setName("Brylle");
p3.setSex('M');
p3.setAge(19);

p1.tellSex();
p1.tellAge();

p2.tellSex();
p2.tellAge();

p3.tellSex();
p3.tellAge();
}
}

Answer

In order to count something, you have to use abstractions that make that easier. So, some hints to get you started:

1) Dont use three variables p1, p2, ... . Learn about arrays or better, List and ArrayList. Like:

List<Person> people = new ArrayList<>();
Person toAdd = new Person("Peter"); toAdd.setSex('M');
people.add(toAdd);
toAdd = new Person("Paul"); toAdd.setSex('M');
people.add(toAdd);
toAdd = new Person("Mary"); toAdd.setSex('F');
people.add(toAdd);

Now you iterate that list; and do counting outside of your class.

int numberOfMales = 0;
int numberOfFemals = 0;

for (Person personToCount : people) {
   if (personToCount.getSex() == 'M') {
      numberOfMales++; 
   else {
      ....

2) Leading to an very important point: your Person class should just be a model for one human being: Therefore it doesn't know anything about gender counts. A person is just that, a single person. Any knowledge about multiple persons, and their genders, and their gender distribution must be outside of that class.

3) Finally, don't use a "char" to represent gender. Read about enums for example. OO programming is about good, helpful abstractions. Using a character to denote a gender is much too low-level to be helpful.