Ask Question
Today, 15:44

Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. Ex: If the input is: n Monday, the output is:

+4
Answers (1)
  1. Today, 18:18
    0
    import java. util. Scanner;

    public class ANot {

    public static void main (String[] args) {

    System. out. println ("Enter a character");

    Scanner in = new Scanner (System. in);

    char character = in. next (). charAt (0);

    System. out. println ("Enter a string");

    String string = in. next ();

    //Calling the method

    System. out. println (countChar (character, string));

    }

    public static int countChar (char a, String in) {

    int counter = 0; / / initialize counter

    for (int i=0; i
    if (a = = in. charAt (i))

    counter++;

    }

    return counter;

    }

    }

    Explanation:

    This program is written in Java Programming language.

    We created a method countChar that returns a integer called counter

    Using a for loop in the method we iterate through the string object and check (a = = in. charAt (i)) so as to increase counter when ever there is a match.

    In the main method a Scanner Class is used to request user to input a character and a string which is passed to countChar when called.

    NOTE that this program has considered lower case letters to be different from upper cases as such a is not equal to A
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers