Java Program to Count Strings and Integers From an Array

You are currently viewing Java Program to Count Strings and Integers From an Array

Java program to count strings and integers from an array

public class ExExceptionToCountStringAndNumericValues {
  public static void main(String arg[]) {
    // enter string u want here.
    String x[] = {
      "Raj",
      "77",
      "101",
      "99",
      "Jio"
    };
    int cn = 0, cs = 0;

    //print array elements
    System.out.println("Array elements are: ");
    for (int i = 0; i < x.length; i++) {
      System.out.println(x[i]);
    }

    // scan the string.
    for (int i = 0; i < x.length; i++) {
      try {
        int j = Integer.parseInt(x[i]);
        cn++;
      } catch (NumberFormatException e) {
        cs++;
      }
    }
    // show the numeric and string value after counting.
    System.out.println("Numeric:" + cn + "\nStrings:" + cs);
  }
}

Output

First run:
Array elements are: 
Raj
77
101
99
Jio
Numeric:3
Strings:2

Second run (with different input)
Array elements are: 
Gwalior
77
Indore
99
Bhopal
Numeric:2
Strings:3

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply