Write a recursive method to return the number of uppercase letters in a String. You need to define the following two methods. The second one is a recursive helper method. public static int count(String str) public static int count(String str, int high) For example, count("WolFIE") returns 4.

Respuesta :

Answer:

Recursive function with two parameters that return the number of uppercase letters in a String

public static int count(String str,int h)//Defining function

{

      if(str.charAt(0)>='A' && str.charAt(0)<='Z')//Checking the characters from A to Z

{

          h++; //incrementing the counter

          if(str.length()>=2){

              return count(str.substring(1),h);//recalling function

          }

      }

      if(str.length()>=2){

              return count(str.substring(1),h); //recalling function

      }

      return h;

  }

This is the recursive function with the name count of return type integer,having parameters str of string type and h of integer type.In this we are checking the characters at a particular position from A to Z.

Recursive function with one parameter that return the number of uppercase letters in a String

public static int count(String str)//Defining function

{

      if(str.charAt(0)>='A' && str.charAt(0)<='Z')//Checking the characters from A to Z

{

          count++; //incrementing the counter

          if(str.length()>=2){

              return count(str.substring(1));//recalling function

          }

      }

      if(str.length()>=2){

              return count(str.substring(1)); //recalling function

      }

      return count;

  }

This is the recursive function with the name count of return type integer,having parameters str of string type .In this we are checking the characters at a particular position from A to Z.

Java program that return the number of uppercase letters in a String

import java.util.*;

public class Myjava{

static int count =0;//Defining globally  

 

public static int count(String str,int h)//Defining function

{

      if(str.charAt(0)>='A' && str.charAt(0)<='Z')//Checking the characters from A to Z

{

          h++;

//incrementing the counter

          if(str.length()>=2){

              return count(str.substring(1),h);//recalling function

          }

      }

      if(str.length()>=2){

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

//recalling function

      }

      return h;

 

  }

  public static void main(String[] args)//driver function

  {

      System.out.println("Enter a string");//taking input

      Scanner scan = new Scanner(System.in);

      String s = scan.nextLine();

      int h =0;

      System.out.println("Counting the Uppercase letters: "+count(s,h));

  }

}

Output

Enter a string  WolFIE

Counting the Uppercase letters: 4