Define a class to accept a String and print the number of digits, alphabets and special characters in the string.

Example:
S = "KAPILDEV@83"
Output:
Number of digits – 2
Number of Alphabets – 8
Number of Special characters – 1

Java Programming Language (Article) (Program)

68

Given Input:

KAPILDEV@83

Expected Output:

No. of Digits = 2
No. of Alphabets = 8
No. of Special Characters = 1

Program:

import java.util.Scanner;

public class RansariCount {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);  // Create Scanner object for input
        System.out.println("Enter a string:");
        String str = in.nextLine();  // Take user input for the string

        int len = str.length();  // Get the length of the input string

        int ac = 0;  // Counter for Alphabets
        int sc = 0;  // Counter for Special characters
        int dc = 0;  // Counter for Digits
        char ch;     // Variable to store each character

        // Loop through each character in the string
        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);  // Get the character at index i

            // Check if the character is a letter
            if (Character.isLetter(ch))  
                ac++;  // Increment the alphabet counter

            // Check if the character is a digit
            else if (Character.isDigit(ch))  
                dc++;  // Increment the digit counter

            // Check if it's a special character (not a letter or digit)
            else if (!Character.isWhitespace(ch))  
                sc++;  // Increment the special character counter
        }

        // Print the results
        System.out.println("No. of Digits = " + dc);
        System.out.println("No. of Alphabets = " + ac);
        System.out.println("No. of Special Characters = " + sc);
        
        in.close();  // Close the Scanner object
    }
}

Output:

No. of Digits = 2
No. of Alphabets = 8
No. of Special Characters = 1

Explanation:

  • User Input: The program takes a string input from the user using a Scanner.
  • Iteration: It iterates over each character in the string.
  • Character Classification: It checks if the character is an alphabet, digit, or special character and increments the respective counters.
  • Output: Finally, it prints the count of digits, alphabets, and special characters in the input string.

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.