I am working on a java program that will count a particular letter in a sentence that the user inputs. Below is the code that I have, but I also want the program to output the sentenced that was typed by the users. Any help would be appreciated.

import java.util.Scanner;

public class CountSent
{
     public static void main(String[]args)
      {
      Scanner cs = new Scanner(System.in);

      int charCount = 0;

        System.out.print("Enter a letter: ");
      char userChar = cs.nextLine().charAt(0);



        System.out.print("Enter a sentence: ");
      String userString = cs.nextLine();


       userString = userString.toLowerCase();
        userString = userString.substring(0, userString.length()-1);



      for (int i = 0; i < userString.length();i++)
      {
              if (userString.charAt(i) == userChar)
                  {
                  charCount++;
                  }
      }
                         System.out.println("\n\n" + charCount + " words contain the letter "+ userChar +".");
                          System.out.println("The character " + userChar + " appears " + charCount +" times in the sentence");
        }
}

This is what is currently being outputted.

----jGRASP exec: java CountSent

Enter a letter: m
Enter a sentence: my name is mike.


3 words contain the letter m.
The character m appears 3 times in the sentence

 ----jGRASP: operation complete.

Edited 3 Years Ago by pyTony: fixed formating

Exacly what Majestics said, just print out the String variable that user sentance was saved as, which happens to be userString seen here

System.out.print("Enter a sentence: ");
String [B]userString[/B] = cs.nextLine();

Edited 4 Years Ago by scheppy: n/a

Thanks for the help. One more thing, how can I get the input to recognize both upper and lower case when the letter is inputed? If I use an upper case for the letter the program doesn't recognize the letter and says the following...

0 words contain the letter M.
The character M appears 0 times in the sentence my name is mik

And why doesn't it print out the last letter in mike?

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