Reputation: 35
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
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