It is very simple program just split the sentence in string array using split() methods of String class and get the length of the array by using the length property of array.
import java.util.*;
class WordCount
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String:");
String str=sc.nextLine();
String []words=str.split(" "); //split the sentence into words
System.out.println("No Of Words : " + words.length);
}
}
Total no space is equal to the ( no of word - 1)
import java.util.*;
class SpaceCount
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String:");
String str=sc.nextLine();
String []words=str.split(" "); //split the sentence into words
System.out.println("No Of Space : " + (words.length-1));
}
}