Saturday, July 25, 2015

Word Count in Java

A program that I wrote in Java that will ask the user to enter a sentence and then our program will count the number of words in a given sentence.

If you have some questions about programming, about my work please send mu an email at jakerpomperada@gmail.comand jakerpomperada@yahoo.com. People here in the Philippines can contact me at  my mobile number 09173084360.

Thank you very much and Happy Programming.





Sample Program Output

Program Listing

/* word_count.java */
/* Written By: Mr. Jake R. Pomperada, MAED-IT */
/* July 15, 2015 */
/* This program will count the number of words in a given sentence by the user */

import java.util.Scanner;

class word_count {

    
    private static int word_count(String phrase)
    {
    if (phrase == null)
       return 0;
    return phrase.trim().split("\\s+").length;
    }

public static void main(String args[])
   {
      String words;
      char ch;

      do {
          Scanner input = new Scanner(System.in);
          System.out.println();
          System.out.print("\t WORD COUNT PROGRAM ");
          System.out.println("\n");
          System.out.print("Kindly enter a word :=> ");
          words= input.nextLine();
          System.out.println();
          System.out.print("The total number of words is " + word_count(words) +".");
          System.out.println();
          System.out.print("\nDo you want to continue (Type y or n) : ");
          ch = input.next().charAt(0);                        
     } while (ch == 'Y'|| ch == 'y');  
          System.out.println();
          System.out.print("\t THANK YOU FOR USING THIS PROGRAM");
          System.out.println("\n\n");    
   }
}


No comments:

Post a Comment