Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

countChar(s,ch) returns the number of times the character ch occurs in the strin

ID: 3728685 • Letter: C

Question

countChar(s,ch) returns the number of times the character ch occurs in the string s. For example, if s="committee" and ch='m' then countChar(s,ch) will return 2. You are to do this recursively.

import java.util.Scanner;


public class Lab12Num3 {


  
     public static int countChar(String str, char character) {


      }
    public static void main(String[] args) {
     
        Scanner sc = new Scanner(System.in);
        //input the string
        String x = sc.nextLine();
        //input the character as a string
        String y = sc.nextLine();
        //get the character
        char ch = y.charAt(0);
        System.out.println(countChar(x,ch ));
      
    }
  
}

Explanation / Answer

import java.util.Scanner;

public class Lab12Num3 {

   public static int countChar(String str, char character) {

      

       int count = 0;

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

           if(str.charAt(i) == character)

               count++;

       return count;

   }

   public static void main(String[] args) {

       Scanner sc = new Scanner(System.in);

       //input the string

       String x = sc.nextLine();

       //input the character as a string

       String y = sc.nextLine();

       //get the character

       char ch = y.charAt(0);

       System.out.println(countChar(x,ch ));

   }

}

/*

Sample run:

this is my first line

c

0

*/