Question

2. Write a recursive method to return the number of occurrences a character c in a string s. c and s should be parameters.java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE IN JAVA:

StringDemo.java file:

import java.util.Scanner ;
public class StringDemo {
   public static int charCount(String s, char c) {
       if(s.length() == 0)
           return 0;
       if(s.length() == 1) {
           if(s.charAt(0) == c)
               return 1;
           return 0;
       }
       if(s.charAt(0) == c)
           return 1 + charCount(s.substring(1), c);
       return charCount(s.substring(1), c);
   }
   public static void main(String[] args) {
      
       Scanner sc = new Scanner(System.in);
       System.out.print("Enter a string : ");
       String s = sc.nextLine();
       System.out.print("Enter a character : ");
       char ch = sc.next().charAt(0);
       System.out.printf("The number of occurences of %c in the string %s = %d", ch, s, charCount(s,ch));
   }

}

OUTPUT:

Problems @ Javadoc Declaration Console X <terminated > String Demo [Java Application] C:\Program FilesVava\jdk-13.0.1\bin\jav

Add a comment
Know the answer?
Add Answer to:
java 2. Write a recursive method to return the number of occurrences a character c in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT