Write a recursive method that finds the number of occurrences of a specified letter in a string using the following method header: public static int count(String str, char a) For example, count("welcome",' e') returns 2. Write a test program that prompts the user to enter a string and a character, and displays the number of occurrences for the character in the string.

Respuesta :

Answer:

//Java program to find the number of occurrences of a specified character in a string.

// Import the required packages.

import java.io.*;

import java.util.*;

//class declaration

class CharacterCount

{

// Main method.

public static void main (string args[ ] )

{

  try

      {

     // Taking the input from the user.

         System. out.print ("Type a string to analyze: ");

     // Creating the scanner class object.

         scanner input = new scanner (system. in);

         String str = input .next();

         System.out.print("Type a character to check: ")

         String temp = input.next();

         char c = temp.charAt(0);

     // Calling the method to get the character count.

         int count = count(str,c);

     // Displaying the result.

         system.out.print In("There are " + count + " " + c + " 's. ");

     // catching the exception.

         catch(Exception e)

         System.out.print In("Exception has occured in the class . Program will exit. ");

      // Exiting the system.

         System.exit(0);

         }

}

// Method to calculate the character count.

public static int count(String str, char a)

  {

    // checking for null string input.

      if(str.equals(""))

      {

       return 0;

      }

      else

      {

      int k = 0;

    // Character matching check.

      if ( str.substring(0, 1) . equals (Character.toString(a)) )

      {

   // Incrementing the counter.

      k++;

      }

   // Recursive call

      k += count(str.substring(1) , a);

              return k;

       }

     }

}

Explanation:

Output should show: Type a string to analyze: welcome

                                   Type a character to check: e

                                   There are 2 e's.

Answer:

//TestCode.java

public class TestCode {

public static int count(String str, char a){

if(str==null || str.length()==0){

return 0;

}

else{

if(str.charAt(0)==a){

return 1+count(str.substring(1), a);

}

else{

return count(str.substring(1), a);

}

 }

 }

public static void main(String[] args) {

System.out.println(count("Welcome", 'e'));

}

}

For more information, visit

https://brainly.com/question/12978649?referrer=searchResults