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
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
KAPILDEV@83
No. of Digits = 2 No. of Alphabets = 8 No. of Special Characters = 1
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
}
}
No. of Digits = 2
No. of Alphabets = 8
No. of Special Characters = 1
Scanner.First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.