I'm writing a program which prompts the user to enter a sentence and then prompt the user to enter a single letter of the alphabet (into a char value). It's also supposed to count and display the number of words containing the letter entered (not case sensitive) and the total number of occurrences of the letter entered (not case sensitive). An example if the user entered the sentence: 'She sells seashells by the seashore.' and the letter 'S', the output from the program would be:
4 words contain the letters S.
8 S are found in the sentence.
import java.util.Scanner;
public class Main
{
public static void main(String[]args)
{
Scanner Scan = new Scanner(System.in);
int charCount = 0;
int numWords = 0;
System.out.println("\n\nThis program asks you to type in a sentence,");
System.out.println("it then requires a single letter of the alphabet");
System.out.println("to be entered in and displays the number of words");
System.out.println("as well as the total number of occurrences.");
System.out.print("Enter a sentence: ");
String userString = Scan.nextLine();
System.out.print("Enter a letter: ");
char userChar = Scan.nextLine().charAt(0);
userString = userString.substring(0, userString.length()-1);
for (int i = 0; i < userString.length(); i++)
{
if (userString.charAt(i) == ' ')
{
numWords += 1;
}
if (userString.charAt(i) == userChar)
{
charCount++;
}
}
System.out.println( numWords + " words contain the letter "+ userChar +".");
System.out.println( charCount + " " + userChar + " are found in the sentence.");
}
}
Now the output is leaning towards the direction I want it, however it prints:
5 words contains the letter S.
8 S are found in the sentence.
Rather than the example:
4 words contain the letters S.
8 S are found in the sentence.
It won't print the correct number of words containing the letter entered by the user. What can I do to make it so it matches the example?