Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Java program to print the counts of chars and digits in the given text.
This can be achieved using “Character” class defined “java.lang” package.
Here is the Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.sample.clearurdoubt; import java.util.Scanner; public class LetterAndDigitCounter { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter some text: "); String userInput = in.nextLine(); int countOfChars = 0, countOfDigits = 0, countOfSpaces = 0, countOfOtherChars = 0; for(Character ch : userInput.toCharArray()) { if(Character.isLetter(ch)) { countOfChars++; } else if(Character.isDigit(ch)) { countOfDigits++; } else if(Character.isSpaceChar(ch)) { countOfSpaces++; } else { countOfOtherChars++; } } System.out.println(); System.out.println("Letters : " + countOfChars); System.out.println("Digits : " + countOfDigits); System.out.println("Spaces : " + countOfSpaces); System.out.println("Other Characters : " + countOfOtherChars); in.close(); } } |
Output:
Happy Learning :).
Please leave a reply in case of any queries