Java program to count the number of words in a sentence

PROGRAM:

import java.util.Scanner;
import java.util.StringTokenizer;
public class NoOfWords {
    static Scanner scan=new Scanner(System.in);
    public static void main(String [] args){
        String s1;
        int count=0;
        System.out.println("Enter the sentence");
        s1=scan.nextLine();
        StringTokenizer stk=new StringTokenizer(s1," ");
        while(stk.hasMoreTokens()==true)
        {
            stk.nextToken();
            count++;
        }
        System.out.println("No. of words= "+ count);
    }
}

OUTPUT:

Enter the sentence
welcome to java programming
No. of words= 4

Popular Posts