116k views
5 votes
Write a method named countMatching(). It has two parameters: a String and a character. The method returns a count of how many times the character parameter appears in the String parameter. Case matters. For example, 'A' is not the same as 'a'. You only need to write the countMatching() method and nothing else (do not modify the main() method provided below). Note, however, that your method must work for any parameters passed, not just the example below.

1 Answer

1 vote

Answer:

Check the explanation

Step-by-step explanation:

public static int countMatching(String s, char c) {

int count = 0;

for (int i = 0; i < s.length(); i++) {

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

++count;

}

return count;

}

Method in a complete Java program

public class FizzBuzz {

/* sample run:

* z appears 2 time(s) in FIZZbuzz

*/

public static void main(String[] args) {

String s = "FIZZbuzz";

char c = 'z';

int count = countMatching(s, c);

System.out.printf("%c appears %d time(s) in %s%n", c, count, s);

}

// Put your countMatching() method here:

public static int countMatching(String s, char c) {

int count = 0;

for (int i = 0; i < s.length(); i++) {

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

++count;

}

return count;

}

}

z appears 2 time(s) in FIZZbuzz Process finished with exit code

Write a method named countMatching(). It has two parameters: a String and a character-example-1
User Havald
by
5.8k points