Ads

Tutorials

# Find in Array - Calculate Occurrences of Elements in Array

This section illustrates you how to calculate occurrences of elements in an array.

This section illustrates you how to calculate occurrences of elements in an array.

# Find in Array - Calculate Occurrences of Elements in Array

This section illustrates you how to calculate occurrences of elements in an array. Occurrences means, the how many times an element occurs in the array. In this section, you will get more and more help from the given following program with the complete code.

Program Description:

This program first asks for the length of the array whatever you want to fix and then it takes some inputs for the elements of the array how more you have mentioned for the length of the array. And finally it show the occurrences of each and every element of the array uniquely.

Here is the code of the program:

 ``` import java.io.*; public class OccurancesInArray{   public static void main(String[] args) throws IOException{   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));   System.out.print("How many elements you want to enter in the array: ");   int num=0;   try{   num = Integer.parseInt(in.readLine());   }   catch(NumberFormatException ne){   System.out.println(ne.getMessage() + " is not a number!");   System.exit(0);   }   String[] elements = new String[num];   int a;   int k;   for(int i = 0; i < num; i++){   elements[i] = in.readLine();   }   for(int i = 0; i < elements.length; i++){   a = 0;   k = 1;   for(int j = 0; j < elements.length; j++){   if(j >= i){   if(elements[i].equals(elements[j]) && j != i){   k++;   }   }   else if(elements[i].equals(elements[j])){   a = 1;   }   }   if(a != 1){   System.out.println("Occurance of \'" + elements[i] + "\' : " + k);   }   }   } }```

Output of the program :

 C:\chandan>javac OccurancesInArray.java C:\chandan>java OccurancesInArray How many elements you want to enter in the array: 5 123 chand 453 aaa 123 Occurance of '123' : 2 Occurance of 'chand' : 1 Occurance of '453' : 1 Occurance of 'aaa' : 1 C:\work\chandan>_

Download this example.

Ads

Ads