Ian
Ian

Reputation: 35

How to count the occurrence of two char values in a given String

public int count_two_chars(String s, char c, char d){
    int counter = 0;
    for(int i=0; i<s.length(); i++){
       if(s.charAt(i) == c + d){
           counter = counter + 1;
       }
    }
    return counter;
}

I need to define this method so that it returns as an int, the number of times either char c or char d is present in String s.

Only methods able to be called on String s are charAt(int) and length.

I would really like some help with this, not just the code because what does that do for me as a new programmer?

Upvotes: 0

Views: 72

Answers (1)

Sinkingpoint
Sinkingpoint

Reputation: 7634

You probably want to count the number of occurances of either char c or char d. This is not achieved by adding them together, this results in an entirely different char altogether.

You nearly had it correct actually, just change your if condition:

if(s.charAt(i) == c || s.charAt(i) == d)

Also, note the || operator to denote OR.

Upvotes: 4

Related Questions