-1

This is supposed to counter the number of a certain character but it keeps returning zero. This is my call in the main System.out.println("Frequency of 'e' = " + charFrequency(stringArray, 'e'));

public static int charFrequency(String[] s, char ch){
    int counter=0;

    for(int i=0; i<s.length; i++){
        if(s.equals(ch)){
            counter++;
        }
        else{
            return 0;
        }

    }
    return counter;
J.Doe
  • 31
  • 2
  • 8
  • 1
    `s` is an array of strings. Will `s` ever be equal to a character? Nope. – ajb Mar 06 '17 at 04:23
  • 1
    When asking about code that doesn't work, you should always include the **expected behavior**, the **actual behavior** and the **complete text/stacktrace for any errors you get**. – azurefrog Mar 06 '17 at 04:23
  • Possible duplicate of [Java: How do I count the number of occurrences of a char in a String?](http://stackoverflow.com/questions/275944/java-how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string) – Atul Mar 06 '17 at 04:24
  • Thank you I'm new to coding – J.Doe Mar 06 '17 at 04:27
  • Also, even if the comparison is done correctly, the first time a non-match is found, the OP's method is going to return 0. – azurefrog Mar 06 '17 at 04:27

6 Answers6

3

You are checking character against String array. You need to check the char against the char in the array

if(s[i].charAt(j) ==ch){
     counter++;
 }

And you are returning wrong.

So your code becomes

   public static int charFrequency(String[] s, char ch) {
        int counter = 0;

        for (int i = 0; i < s.length; i++) {
            for (int j = 0; j < s[i].length(); j++) {
                if (s[i].charAt(j) == ch) {
                    counter++;
                }
            }
        }

        return counter;
    }
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

If you are going to use this method several many times for different chars then it is reasonable to collect all frequences and just use this data:

public static Map<Character, Long> charFrequency(String[] s){
    return Stream.of(s)
            .map(CharSequence::chars)
            .flatMap(x -> x.mapToObj(y -> (char)y))
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

public void test() {

    String s[] = {"banana", "apple", "orange"};
    Map<Character, Long> frequencies = charFrequency(s);

    System.out.println(frequencies);
    System.out.println(frequencies.get('a'));
}

Output:

{p=2, a=5, r=1, b=1, e=2, g=1, l=1, n=3, o=1}
5
Dmitry Gorkovets
  • 2,208
  • 1
  • 10
  • 19
  • If you translate this into words, I think even beginners will be able to understand the simple combination of simple operations that match the requirements (and extend, as you proposed). – Tom Blodget Mar 06 '17 at 12:12
1

Why don' you use foreach instead of looping through each time?

private static int findFrequency(String[] array, character character){
    int totalCount = 0;
    for(int i=0;i<array.length;i++) {
        for(character ch : array[i].toCharArray()){
            if(ch == c)
                totalCount++;
        }
    }
    return totalCount;
}
Pratik Ambani
  • 2,523
  • 1
  • 18
  • 28
1

You can do it very very easily just like this: The most fast way without any for loop

Just one line of code:

return str.split(Pattern.quote(""+ch), -1).length-1;
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
  • It was because of parentheses. I tried it is working well. without any problem. – Bahramdun Adil Mar 06 '17 at 04:51
  • 2
    OK, after all of your edits, it finally works. My opinion is that this is an ugly way of doing it - Suresh Atta's solution is very much better. But I have removed my downvote. Seriously though, something this elementary is something that you really ought to be able to get _right first time_, not right _three edits later_. – Dawood ibn Kareem Mar 06 '17 at 04:56
  • @DavidWallace OK thank you very much, there can be lot of ways to do so. But could try some different ways to be good practice for to know any problem can have very short answer. We must change the feature. – Bahramdun Adil Mar 06 '17 at 05:00
  • @DavidWallace We must not always relay to the classic solutions, we can have new things to use. – Bahramdun Adil Mar 06 '17 at 05:01
  • 1
    Someone who is posting a question like this is a new programmer who needs to learn the fundamentals. An answer like this isn't helpful to new programmers and may be harmful. (However, it could be interesting to more experienced programmers reading this site later.) Also, writing a "very short answer" may be a way of showing off your cleverness, but it's not important if the goal is to write maintainable software that others can easily read later. – ajb Mar 06 '17 at 05:11
  • @BahramdunAdil You don't need the `(str+". ").split()` You can use `return str.split("s", -1).length-1;` See http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int) – Michael Markidis Mar 06 '17 at 05:17
  • 1
    @ajb Yes you are the most right. But there is a lot of fundamental answer (except this answer) which can the person who asked the question can have the choice to select an answer besides can learn more from the other answers, it can be a good place to learn more things. Hope you understand me the point. – Bahramdun Adil Mar 06 '17 at 05:20
  • @MichaelMarkidis Oh you are right. Thanks! that good point. Nice!! – Bahramdun Adil Mar 06 '17 at 05:20
0

Here's how you can accomplish this:

public static int charFrequency(String[] stringArray, char ch)
{
    int counter = 0;

    // loop through each String in the array
    for (int i = 0; i < stringArray.length; i++)
    {
        String s = stringArray[i];

        // in case the string is null
        if (s != null)
        {
            // loop through each char in the string
            for (int j = 0; j < s.length(); j++)
            {
                if (s.charAt(j) == ch)
                    counter++;
            }
        }
    }
    return counter;
}
Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
0

The traditional for loop version of Dmitry Gorkovets's answer :

public static void main(String[] args) throws Exception {
    int freq[] = getFrequency(new String[] {"banana", "apple", "orange"});
    System.out.println("Frequency of a : "+freq['a']);
    System.out.println("Frequency of p : "+freq['p']);
}

static int[] getFrequency(String inputs[]) {
    int op[] = new int[150]; // The max ascii is of 'z' which is 122.
    for (String ip : inputs) {
        char c[] = ip.toCharArray();
        for (char x : c) {
            op[x]++;
        }
    }
    return op;
}

Output :

Frequency of a : 5
Frequency of p : 2
Community
  • 1
  • 1
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
  • 150 should be 65536 because `char` ranges from 0 to 65535. (There are a lot more letters beyond 'z', even assuming that the focus in on letters that UTF-16 encodes as a single code unit.) – Tom Blodget Mar 06 '17 at 16:51
  • @TomBlodget I completely agree! I kept is 150 just for sake of example. And in the most real life scenario I have come across where it is needed to find the frequency, the input string is alpha numeric with commonly used symbols for which size of 150 is sufficient – Anand Undavia Mar 07 '17 at 05:42