Write a Java program to Counts the number of digits, alphabets, and special characters in a queue of strings


The Java code defines a class CountCharactersInQueue with a method countCharacters that counts the number of digits, alphabets, and special characters in a given Queue of strings.

  • The countCharacters method takes a Queue<String> named queue as input and counts the number of digits, alphabets, and special characters in each string present in the queue.
  • The method initializes three variables: digitCount, alphabetCount, and specialCharCount to 0. These variables will be used to keep track of the counts for each category.
  • The method uses a while loop to process each string in the queue until the queue becomes empty. In each iteration, the poll() method is used to remove and retrieve the first string from the queue.
  • For each character in the current string, the method checks its type using the Character.isDigit(), Character.isLetter(), and else clauses. If the character is a digit, the digitCount is incremented. If it is an alphabet, the alphabetCount is incremented. Otherwise, it is considered a special character, and the specialCharCount is incremented.
  • After processing all characters in the current string, the loop moves on to the next string in the queue.
  • After processing all strings in the queue, the method prints the counts for digits, alphabets, and special characters using System.out.println().
  • In the main method, a Queue<String> named queue is created using the LinkedList implementation of the Queue interface. A single string "Hello1234 @#$" is added to the queue using the offer() method.
  • The countCharacters method is then called with the queue as an argument, and it counts the characters in the string "Hello1234 @#$".

Source Code

import java.util.*;
 
public class CountCharactersInQueue
{
	public static void countCharacters(Queue<String> queue)
	{
		int digitCount = 0;
		int alphabetCount = 0;
		int specialCharCount = 0;
 
		while (!queue.isEmpty())
		{
			String str = queue.poll();
 
			for (int i = 0; i < str.length(); i++)
			{
				char ch = str.charAt(i);
				if(Character.isDigit(ch))
				{
					digitCount++;
				}
				else if(Character.isLetter(ch))
				{
					alphabetCount++;
				}
				else
				{
					specialCharCount++;
				}
			}
		}
 
		System.out.println("Number of Digits : " + digitCount);
		System.out.println("Number of Alphabets : " + alphabetCount);
		System.out.println("Number of Special Characters : " + specialCharCount);
	}
 
	public static void main(String[] args)
	{
		Queue<String> queue = new LinkedList<>();
		queue.offer("Hello1234 @#$");
 
		countCharacters(queue);
	}
}

Output

Number of Digits : 4
Number of Alphabets : 5
Number of Special Characters : 4

Example Programs