Write a method called countChar which accepts a string parameter and a character parameter and returns an integer, that is:
int countChar (String s, char c)
This method should count the number of occurrences of the character c within the string s, and return the count to the caller.
Also write a main method that tests countChar. All of the print statements and user interaction belong in the main method, not in countChar.
import java.util.Scanner; public class CountCharacters { public static int countChar(String s, char c) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) ++count; } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a line of string: "); String s = in.nextLine(); System.out.print("Enter a character: "); char ch = in.next().charAt(0); System.out.println(countChar(s, ch)); } }
Get Answers For Free
Most questions answered within 1 hours.