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 read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.