How to count strings and integers from an array of strings in Java

1 Answer

0 votes
public class Program {
    static int countnum = 0, countstr = 0;
    
    static void count_strings_and_integers(String arr[]) {
        int len = arr.length;

        for (int i = 0; i < len; i++) {
            try {
                int num = Integer.parseInt(arr[i]);
                countnum++;
            } catch (NumberFormatException e) {
                countstr++;
            }
        }
        
        
    }
    
    public static void main(String[] args) {
        String arr[] = {
              "java",
              "888",
              "9",
              "c",
              "python",
              "109",
              "c++"
        };
        
        count_strings_and_integers(arr);
        
        System.out.println("Numbers: " + countnum + "\nStrings: " + countstr);
    }
}




/*
run:

Numbers: 3
Strings: 4
  
*/

 



answered Feb 17, 2024 by avibootz
edited Feb 17, 2024 by avibootz

Related questions

1 answer 131 views
1 answer 220 views
1 answer 114 views
1 answer 220 views
...