1

I want to count number of integer and string elements in array. My code has some logical error. It shows the number of string incorrect but not showing the number of integer elements. I am working with string so it skips the first iteration. To execute the first statement i created the dummy variable.

String dummy;

      int size_of_Array;
        System.out.println("Enter the size of Array:");
        size_of_Array=input.nextInt();

        String [] Array=new String[size_of_Array];
        for(int i=0; i<size_of_Array; i++){
            System.out.print("["+i+"] :");
            dummy=input.next();
            Array[i]=input.nextLine();
        }
        int count1 = 0, count2=0;
        for(int j=0; j<size_of_Array; j++){
            try{
                int k=Integer.parseInt(Array[j]);
                count1++;
            }catch(NumberFormatException e){
                count2++;
            }
        }
        // numeric and string values after counting
            System.out.println("Numeric: " +count1+ "\nString: " +count2);   
    }

Here is the output of code:
Enter the size of Array: 3

[0] :abc
[1] :abc
[2] :3
Numeric: 0
String: 3

Expected output is:

    [0] :abc
    [1] :abc
    [2] :3
    Numeric: 1
    String: 2
Willy William
  • 69
  • 1
  • 8

0 Answers0