36,679 views
7 votes
7 votes
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. Ex: If the input is: n Monday the output is: 1 Ex: If the input is: z Today is Monday the output is: 0 Ex: If the input is: n It's a sunny day the output is: 2

User Daerik
by
3.0k points

1 Answer

20 votes
20 votes

Answer:

import java.io.*;

public class Main {

public static void main(String[] args) throws IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String s;

while ((s = in.readLine()) != null) {

int total = 0;

for (char character : s.toCharArray()) {

if (s.charAt(0) == character) {

total++;

}

}

System.out.println(total - 1);

}

}

}

Step-by-step explanation:

We start the program by using the BufferedReader which will allow input from the user.

Then, we create a variable String that will take the input from the user.

Since the problem is asking us for the total number of times that the specified character appeared in the String, we will have to iterate over that String and count every time the character is found.

For this, I initialized an integer variable total, that takes count every time the character is found.

Using a for each loop, I converted the string to a character array (e.g. instead of a String "Monday", it will now look like {"M", "o", "n", "d", "a", "y"). It will iterate for each character it finds and checks if the character at position 0 is the same as the character at position i.

If the condition is true, then the total will increment by one.

But the problem is, since we converted the string into a character array to validate each character, the initial character will also add to the sum. So for "n Monday", it will take the first n, and add the total + 1.

Without specifying total - 1, "n Monday" will output 2 since there are two total "n".

There is a limitation, which wasn't specified in the problem statement anyway, but it's good to be aware of in case you need to solve it. If you want to check all of the characters that must equal the character you want to validate, irrespective of upper or lowercase, you will have to convert the string to lowercase first, so that the program will take the uppercase letters into account as well.

For that, before the for each statement, simply add s = s.toLowerCase();

User Adam Shamsudeen
by
3.0k points