Dremendo Tag Line

Input sentence and count the number of words in it in Java

String - Question 2

In this question, we will see how to input a sentence and count the number of words in it in Java programming. To know more about string click on the string lesson.

Q2) Write a program in Java to input a sentence and count the number of words in it. Assume that there may be any number of blank spaces between the words.

Program

import java.util.Scanner;

public class Q2
{
    public static void main(String args[])
    {
        String s;
        int i,wc=0;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a sentence");
        s=sc.nextLine();

        for(i=0; i<s.length(); i++)
        {
            if(i==0 && s.charAt(i)!=' ')
            {
                wc++;
            }
            else if(s.charAt(i)==' ' && s.charAt(i+1)!=' ')
            {
                wc++;
            }
        }
        System.out.println("Total words = "+wc);
    }
}

Output

Enter a sentence
We are    free to  take  our    own decision
Total words = 8
video-poster