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
Topic: Counting digits, alphabets and special characters
Answer
import java.util.Scanner;
class CountChars { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a String : "); String s = sc.nextLine();
int dig = 0, alp = 0, spl = 0; char ch;
for(int i = 0; i < s.length(); i++) { ch = s.charAt(i); if(Character.isDigit(ch)) dig++; else if(Character.isLetter(ch)) alp++; else spl++; }
System.out.println("Number of digits - " + dig); System.out.println("Number of Alphabets - " + alp); System.out.println("Number of Special characters - " + spl); } }
The standard character-classification pattern: loop through the string with charAt(i) and send each character to one of three counters.
The structure to notice is if / else if / ELSE. The final else needs no test at all — anything that is neither a digit nor a letter must be a special character. Writing a third condition would risk missing something (a space, say) and leaving it uncounted.
Use the Character class methods isDigit() and isLetter() rather than ASCII range comparisons; they are clearer and handle every case correctly.
Read the input with nextLine(), not next(), so that a string containing spaces is read whole. Note that a space would then be counted as a special character — mention that assumption if your string has any.
Trace "KAPILDEV@83": eight letters, two digits (8 and 3) and one special character (@) — matching the question exactly.
s String - the string entered by the user ch char - holds each character of s in turn dig int - counter for digits alp int - counter for alphabets spl int - counter for special characters i int - loop variable, the index into the string sc Scanner - object used to read input