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.

Recommended Answers

All 7 Replies

Print out the original string u got

System.out.print(userString);

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();

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?

you could also have given a reference to the actual String api, giving information about that method

String api

you could also have given a reference to the actual String api, giving information about that method

String api

agree

Member Avatar for hfx642

Take out the -1 in your substring... (Why are you doing a substring?)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.