3 A. Write a Java program to count the letters, spaces, numbers and other characters of an input string.

 public class Example {

 

   public static void main(String[] args) {

 

      String str = "The cat in that hat has 4 feet.";

 

      char[] ch = str.toCharArray();

      int letter = 0;

      int space = 0;

      int num = 0;

      int other = 0;

      for (int i = 0; i < str.length(); i++) {

         if (Character.isLetter(ch[i])) {

            letter++;

         } else if (Character.isDigit(ch[i])) {

            num++;

         } else if (Character.isSpaceChar(ch[i])) {

            space++;

         } else {

            other++;

         }

      }

      System.out.println(str);

      System.out.println("Letters: " + letter);

      System.out.println("Spaces: " + space);

      System.out.println("Numbers: " + num);

      System.out.println("Other: " + other);

   }

}


Comments

Popular posts from this blog

Program using Light Sensitive Sensors on Tinkercad

Custom Buttons in Android

Blink LED pattern using Arduino on Tinkercad