How to count string and integer elements in an array
The blog provides the technical approach on ” How to count String and Integer element count in one dimensional array in java ?
Problem Statement:
Java program to count String and Integer element count in one dimensional array
Solution Approach:
- Get Array Count as User Input
- Get Array Elements as User Input
- Iterate the Array elements
- If the Array element is parsed as Integer, increment the count for integer in a variable
- If the Array element is NOT parsed as Integer, increment the count for string in a variable
- Print the Total Count for Integer and String elements in one dimensional array
package com.java.planforexams.array; import java.util.Scanner; public class CountStringIntegerInArray { public static void main(String[] args) { int stringCount =0; int intgerCount =0;; // Scanner object for reading User Input Scanner scan = new Scanner(System.in); // Enter Row Count System.out.print("Enter One Dimensional Array Count : "); int count= scan.nextInt(); String OneDimensionalWithStringAndIntegers[]=new String[count]; System.out.println("Array elements are: "); // Iterate the array elements for (int incr=0; incr<count; incr++) { OneDimensionalWithStringAndIntegers[incr] = scan.next(); } // scan the string. for(int incr=0; incr < count; incr++) { try { int j=Integer. parseInt(OneDimensionalWithStringAndIntegers[incr]); intgerCount++; } catch(NumberFormatException e) { stringCount++; } } System.out.println("Total Integer Element in 1-Dimensional Array is ::::"+intgerCount+ "\n"); System.out.println("Total String Element in 1-Dimensional Array is ::::"+stringCount+ "\n"); } } Output: Enter One Dimensional Array Count : 5 Array elements are: Mohit Rohit Mihika 21 11 Total Integer Element in 1-Dimensional Array is ::::2 Total String Element in 1-Dimensional Array is ::::3
Leave a Reply