Home »
Java programs
Java program to count number of words in a sentence
In this Java program, we will learn how to count the number of uppercase and lowercase letters in a given string?
Submitted by Jyoti Singh, on October 05, 2017
Problem statement
Given a sentence and we have to count total number of words using Java program.
Example
Input sentence: "I love programming"
Output:
Number of letters: 3
In this code we have one input:
A string input (It will be a sentence entered by the user which needs to be checked).
For each string we will have two outputs
The number of words in sentence
Java program to count number of words in a sentence
Consider the program: It will take number of inputs, sentences or string and print total number of words.
import java.util.Scanner;
public class ToCountNumberOfWords{
public static void main(String[] args) {
//Scanner is a class used to get the output from the user
Scanner Kb=new Scanner(System.in);
//Input sentence from the user
System.out.println("Enter a sentence!");
/*hasNext is a function of Scanner class which checks whether the next line is present or not
if the line is present the code will continue to run
but if the next line is not present the code will be terminated
*/
while(Kb.hasNext()){
//nextLine is a function of Scanner class to read the input line
String line=Kb.nextLine();
/* this string will contain the words that are split or we can say break by the split function
split function takes parameter i.e from where we have to split the string
here,that parameter is a space as soon as it will find a space,it will break that into substring from there
and store them in string array arr with an index
*/
String[] arr=line.split(" ");
//counter to count the number of words initialized to zero
int word=0;
//looping to count the number of words in array
for(int i=0;i<arr.length;i++){
word++;
}
//print the number of words in a sentence
System.out.println(word);
}
}
}