Java program to count number of words in a given string

Written by Nikunj Pathak. Posted in Basic

This is a java program that counts number of words in a given String

import java.util.*;
/*Accepting the string using Scanner class which is imported from java.util*/
public class Test {
    public static void main(String args[]){
        Scanner scan=new Scanner(;
        String inputSentence;
            System.out.println("Please enter a Sentence");
            if(!inputSentence.isEmpty()){    //Once we have a legit input we break out of the loop
        // This loop basically makes sure that the user enters a valid sentence(atleast- a letter)
        boolean previousCharWhiteSpace=true;  //just a flag
        int wordCount=0;
        int i;
        for( i=0;i<inputSentence.length();i++){
            if(inputSentence.charAt(i) ==' ' && !previousCharWhiteSpace){
            else if(!(inputSentence.charAt(i) ==' ')){
        /*the for loop increments the word count if a space is encountered between words,for
        multiple spaces between words it wont update the counter-hence the use of the boolean flag.*/
        if(!(inputSentence.charAt(i-1)==' ')){wordCount++;}
        //just to make sure that we count the last word in the sentence as well
        System.out.println("No of words-" + wordCount);
This programproduces correc output for sentences like "          hello world" or "Hello       World" or "Helloworld         "


output of counting number of words

меня зовут эрл