Java Code to Count Occurrence of Word in Sentence - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Monday, September 25, 2017

Java Code to Count Occurrence of Word in Sentence

Write a Java Code to Count Occurrence of Word in Sentence

Program:
/* Java Program Example - Count Occurrence of Word in Sentence */

import java.util.Scanner;

public class JavaProgram
{
public static int countWords(String str)
{
int count = 1;
for(int i=0; i<=str.length()-1; i++)
{
if(str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
count++;
}
}
return count;
}
public static void main(String args[])
{
String sentence;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a Sentence : ");
sentence = scan.nextLine();

System.out.print("Total Number of Words in Entered Sentence is " + countWords(sentence));
}
}

Output:
Enter the sentence:This is a Java Program

Total number of words in the Entered sentence is 5

No comments:

Post a Comment