Home Tutorial Java Core Java count occurrence of number from array

 
 

Share on Google+Share on Google+
Java count occurrence of number from array
Posted on: August 19, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to count the occurrence of numbers andfind the number which has the highest occurrence.

Java count occurrence of number from array

Here we have created an example that will count the occurrence of numbers and find the number which has the highest occurrence. Now for this, we have created an array of 15 integers and accepted the numbers through the console. We have restricted to enter the number above 6, only (0-6 ) are allowed. If a number is not within this range, program will ask for another number. Then using the ArrayList we determined the occurrence of each element of the array.

Here is the code:

import java.util.*;

public class Search {
	public static void searchAndDisplay(int[] arr) {
		ArrayList list1 = new ArrayList();
		ArrayList list2 = new ArrayList();
		for (int element : arr) {
			int index = list1.indexOf(element);
			if (index != -1) {
				int newCount = list2.get(index) + 1;
				list2.set(index, newCount);
			} else {
				list1.add(element);
				list2.add(1);
			}
		}
		for (int i = 0; i < list1.size(); i++) {
			System.out.println("Number " + list1.get(i) + " occurs "
					+ list2.get(i) + " times.");

		}
		int maxCount = 0;
		int index = -1;
		for (int i = 0; i < list2.size(); i++) {
			if (maxCount < list2.get(i)) {
				maxCount = list2.get(i);
				index = i;
			}
		}
		System.out.println("Number " + list1.get(index)
				+ " has highest occurrence i.e " + maxCount);
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int[] arr = new int[15];
		System.out.println("Enter 15 integers (0-6):");
		for (int i = 0; i < arr.length; i++) {
			int num = input.nextInt();
			if (num <= 6 && num >= 0) {
				arr[i] = num;
			} else {
				System.out.print("Enter another number: ");
				num = input.nextInt();
			}
		}
		searchAndDisplay(arr);
	}
}

Output:

Enter 15 integers (0-6):
7
Enter another number: 1
2
3
4
5
3
3
5
6
9
Enter another number: 3
3
2
1
6
4
Number 0 occurs 2 times.
Number 2 occurs 2 times.
Number 3 occurs 4 times.
Number 4 occurs 2 times.
Number 5 occurs 2 times.
Number 6 occurs 2 times.
Number 1 occurs 1 times.
Number 3 has highest occurrence i.e 4
Advertisement

Related Tags for Java count occurrence of number from array:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 19, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com