Ask Question
29 November, 10:28

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:

+2
Answers (1)
  1. 29 November, 12:29
    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?
Get 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 & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers