Ask Question
18 September, 12:50

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. 18 September, 13:10
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers