Write a Java method to count all words in a string


This Java program prompts the user to enter a string and then counts the number of words in the string. Here's a step-by-step explanation of how the program works:

  • The program begins by importing the Scanner class, which is used to read user input from the command line.
  • The main method is defined, which is the entry point of the program.
  • A new Scanner object is created and assigned to the variable input.
  • The program prompts the user to enter a string by calling System.out.print() method with the message "Enter the String: ".
  • The user enters a string, which is read by calling the nextLine() method on the Scanner object input, and is assigned to the variable str.
  • An integer variable count is declared and initialized to zero. This variable will be used to keep track of the number of words in the string.
  • The program checks if the first or last character of the string is a space by using the substring() method to extract the first and last characters of the string and comparing them to a space character. If either the first or last character is not a space, it means that the string contains at least one word.
  • If the string contains at least one word, a for loop is used to iterate over each character in the string, starting from the first character (which has index 0) and ending with the last character (which has index str.length() - 1).
  • For each character in the string, the program checks if it is a space by comparing it to a space character. If the character is a space, the count variable is incremented.
  • After the for loop finishes iterating over all the characters in the string, the program increments the count variable by 1 to account for the last word in the string.
  • The program prints the number of words found in the string by calling System.out.print() method with the message "Number of words in the string : " concatenated with the value of the count variable.

Source Code

import java.util.Scanner;
public class Count_Words
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the String : ");
		String str = input.nextLine();
		int count = 0;
		if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1))))
		{
			for (int i = 0; i < str.length(); i++)
			{
				if (str.charAt(i) == ' ')
				{
					count++;
				}
			}
			count = count + 1; 
		}
		System.out.print("Number of words in the string : " +  count);
	}
}

Output

Enter the String : Tutor Joes Computer Education
Number of words in the string : 4

Example Programs