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?

Your output isn't correct because you are only checking to see how many words exist in your input, not how many words have the letter you are looking for. You might want to do something like

Scanner input = new Scanner(System.in);
int wordsWithTheLetter = 0;
while(input.hasNext()){
String word = input.next();
for (int i = 0; i < word.length(); i++){
if (word.charAt(i) == yourChar){
wordsWithTheLetter++;
break;
}
}
}

Usually I wouldn't give this much code, but in your case it looks like you've already put forth a lot of effort and you aren't very far from a solution. I'll leave integrating that example into your code up to you. Keep in mind it isn't the only way to solve your problem, and your approach of trying to do both at once (count words and count characters) is slightly more efficient. But in this case I'd trade efficiency for clarity as it is easier to write two separate pieces of code.

Edited 6 Years Ago by BestJewSinceJC: n/a

Thank you very much for your help, I appreciate it.
However when I tried to assemble the coding as you did, as counting both words and letters, my program stumbled on an endless run.

I accidentally left the prompt out in the snippet I gave you. Obviously you need to prompt the user for input and allow them to enter some input, otherwise it will not run correctly. Oh, and you could also add each word that they input to an ArrayList. Then use a for loop on each word in the ArrayList to count the letters.

Pardon my ignorance, but is there an alternative to an ArrayList? I'm not quite familiar with arrays.

There are alternatives but ArrayList is probably the easiest type of collection you can use. ArrayList isn't an array, but it uses an array in the underlying implementation. An array is just a chunk of contiguous memory that can hold things; an ArrayList is a java Object. The ArrayList class offers up methods that allow the user easy access to elements held in the underlying array. For example you could do stuff like the following:

ArrayList<String> list = new ArrayList<String>();
list.add("WOOHOO");
if ("WOOHOO".equals(list.get(0)) System.out.println("They're the same");

So you see it is pretty simple to add stuff to an ArrayList and get stuff back out of it.

Anyway, that being said you do not have to use an ArrayList to solve this problem. I was just offering it up as one way to do it. Taking your original code, check out my edits:

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) == userChar)
                                    {
                                    charCount++;
                                    }

              }

Scanner countWords = new Scanner(userString);
int wordsWithTheLetter = 0;
while(countWords.hasNext()){
String word = input.next();
for (int i = 0; i < word.length(); i++){
if (word.charAt(i) == userChar){
wordsWithTheLetter++;
break;
}
}
}

              System.out.println( numWords + " words contain the letter "+ userChar +".");
              System.out.println( charCount + " " + userChar + " are found in the sentence.");
        }
}

Notice that you can create a Scanner which scans through a String; all I did was do that and combine it with the code snippet I gave you earlier. Anyway keep in mind that me giving away this much code is frowned upon and usually I would not do so, but I felt like I'm making the issue confusing for you, so I wanted to clarify things.

This article has been dead for over six months. Start a new discussion instead.