write a method that finds the number of occurences in a stri

write a method that finds the number of occurences in a string using the following header: public stat int count( string str, char a) add a main method to the class that tests the method by prompting for a string and a character, invoking the method and printing the returned count.

SAMPLE RUN: JAVA CHARCOUNTER

enter a string: Hello

enter a character: H

H occurs 1 times in the string

Solution

Hi, Please find my code.

Plese let me know in case of any issue:

import java.util.Scanner;

public class CountCharacters {

  

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

      

       // base case

       if(str == null)

           return 0;

      

       int count = 0;

      

       // iterate through each character of str and check whether current character is equal to a

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

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

               count++;

       }

      

       return count;

   }

  

   public static void main(String[] args) {

      

       Scanner sc = new Scanner(System.in);

      

       System.out.print(\"Enter string: \");

       String str= sc.nextLine();

      

       System.out.print(\"Enter a character: \");

       char c = sc.next().charAt(0); // getting 1st character from input

      

       int countC = count(str, c);

      

       System.out.println(c+ \" occeurs \"+countC+\" times in string\");

   }

}

/*

Sampele Run:

Enter string: Hello

Enter a character: H

H occeurs 1 times in string

*/

write a method that finds the number of occurences in a string using the following header: public stat int count( string str, char a) add a main method to the c
write a method that finds the number of occurences in a string using the following header: public stat int count( string str, char a) add a main method to the c

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site