This program reads a string from the user and then counts the total number of words in the string. Here's how it works:
import java.util.Scanner; class NumberOf_Words { public static void main(String args[]) { String text; int count=0; Scanner input = new Scanner(System.in); System.out.print("Enter the String : "); text = input.nextLine(); for(int i=0; i<text.length()-1; i++) { if(text.charAt(i)==' ' && text.charAt(i+1)!=' ') count++; } System.out.println("Total Number of Words in String : "+ (count+1)); } }
Enter the String : Wlecome Java Programs Total Number of Words in String : 3
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions