-2

I wanted to know how many males and females in my array. Using the words (M) and (F) as indicator. I currently have no idea how to do it.

Here's my array:

String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};  
7
  • 5
    Loop over array, check if each element in the array endswith (F) or (M)? Commented Jul 9, 2014 at 8:45
  • for(String s: ppl){ if (s.contains("(M)") male++} female=ppl.length-male; Commented Jul 9, 2014 at 8:48
  • how do i check for the array using the (f) and (m) ? Commented Jul 9, 2014 at 8:49
  • That is what everyone else is telling you. (in comments and in answers) LOL Commented Jul 9, 2014 at 8:50
  • @Harry Not a duplicate of that one. Commented Jul 9, 2014 at 8:57

8 Answers 8

9

In Java 8 you can do this.

String[] ppl = {"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
long male = Stream.of(ppl).filter(s -> s.endsWith("(M)")).count();
long female = Stream.of(ppl).filter(s -> s.endsWith("(F)")).count();

You can add .toUpperCase() if you don't know the case, and/or use .contains instead of .endsWith if you don't know where the (F) might be.

Sign up to request clarification or add additional context in comments.

5 Comments

your ans is good demo of aggregate functions and lamdas but it hardly seems the user is even aware of java1.5/6
If you can assume everyone is either male or female, long female = ppl.length - male would be quicker for long lists.
@Shail016 I agree, and most likely this is homework the OP should be working out for themselves ;) but answering using Java 8 is more likely to be interesting to more people.
@Trengot I didn't want to suggest a female is a "not male" or males are the ones worth counting. ;)
@Shail016 I try to give an answer to homework questions which are both informatively but a student couldn't pass off as their own work. ;)
2

Here is my solution:

String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
int maleCount = 0;
for (String str : ppl) {
  if (str.trim().toUpperCase().endsWith("(M)")) {
    maleCount++;
  }
}

System.out.println("Male count: " + maleCount);
System.out.println("Female count: " + (ppl.length - maleCount));

Result:

Male count: 4
Female count: 2

Explanation: You now the size of input (array.length()). You just need to count all the Males (or Females) and other can be derived.

3 Comments

what if the (m) and (f) is found in the beginning or in the middle of the string?
You can use toUpperCase().
for anywhere you can use contains()
1

Here is the code sample -

public static void main(String[] args) {
    String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
    int maleCount = 0;
    int femaleCount = 0;
    for (int i = 0; i < ppl.length; i++) {
        if(ppl[i].contains("(M)")){
            maleCount++;
        }
        if(ppl[i].contains("(F)")){
            femaleCount++;
        }
    }
    System.out.println("maleCount: "+maleCount);
    System.out.println("femaleCount: "+femaleCount);
    }

Output :

maleCount: 4
femaleCount: 2

2 Comments

I think you mean male and female ;)
for-each and else-if would be better..:)
1
String[] arr = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
    int maleCount=0,femaleCount=0;
    for(String element : arr){
        if(element.endsWith("(F)")){
            femaleCount++;
            System.out.println(element +" is Female");
        }else if(element.endsWith("(M)")){
            maleCount++;
            System.out.println(element +" is Male");
        }
    }
    System.out.println("Total males "+maleCount +" Total Females "+femaleCount);

Comments

1

Untested, but this should get you most of the way there. This isn't a hash like "Karen" => "F".. but the part ".substring(-3)" should count the occurences of (F) and (M).. have a look at this question

String[] arr = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
Integer counter = 0;
String lastItem = arr[0];
for(int i = 0; i < arr.length; i++)
{
    if(arr[i].substring(-3).equals(lastItem))
    {
        counter++;
    }
    else
    {
        itemCount.add(counter);
        counter = 1;
    }
    lastItem = arr[i];
}
itemCount.add(counter);
Integer[] Counts = itemCount.toArray(new Integer[itemCount.size()]);

Comments

1

I've found this code easy to use and understand (no iteration needed):

String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
    String ss=Arrays.toString(ppl).replaceAll("[\\[\\]]", "");
    int malecount = ss.split("(M)").length - 1;
    int femalecount = ss.split("(F)").length - 1;

:)

Comments

0
  String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
      int k,m=0,f=0;
      for( k=0;k<ppl.length;k++)
      {
      if(ppl[k].contains("(F)"))
          f=f+1;
        if(ppl[k].contains("(M)"))
          m=m+1;  
      }

Comments

0

Try to represent the data with classes and enums instead, so you seperate the name from the gender.

Define gender:

public enum Gender {
     MALE, FEMALE, SHEMALE_WTF;
}

Define a person:

public class Person {
    private String name;
    private Gender gender;

    public Person(String name, Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }
    public Gender getGender() {
        return gender;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
       return name;
    }

    public boolean isGender(Gender gender) {
       return this.gender == gender;
    }
}

Now we can create a person simply by writing:

Person karen = new Person("Karen", Gender.FEMALE);

Lets check if 'karen' is a male:

if(karen.isGender(Gender.MALE)) {
     //Ok, karen is a male
}
else {
     //karen is not a male
}

Lets create a Person array instead of your String array:

Person[] ppl = new Person[]{new Person("Karen", Gender.FEMALE),new Person("Kevin", Gender.MALE),new Person("Lee", Gender.MALE),new Person("Joan", Gender.FEMALE),new Person("Des", Gender.MALE),new Person("Rick", Gender.MALE)};

Now lets do the counting:

int females = 0;
int males = 0;


for(Person person : ppl) {
     switch(person.getGender()) {
         case Gender.MALE: 
              males++;
              break;
         case Gender.FEMALE:
              females++;
              break;
         case Gender.SHEMALE_WTF:
              //hmm?
              males++;
              females++;
              break;
              // but I would just:
              // throw new SecurityException("SYSTEM GOT VIRUS!!!!");

      }
 }

Now you have a code that is easy to read.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.