# Thread: Count occurances in array

1. Member Join Date
Nov 2012
Posts
2
Rep Power
0

## Count occurances in array

Hello, I am new to java and am trying to count the highest occruance that appears in an array but I'm not entirely sure how to do this

so far I've got

public class counter {
public static void main(String[] args) {
final int N = (args.length);
int count= 1;
int[] a;
a = new int[N];
for (int i = 0; i < N; i++)
a[i] = Integer.parseInt(args[i]);
for (int i = 0; i < N; i++)
for(int j = i+1; j<N; j++)
if (a[i] == a[j]) {
count++;
}

System.out.println(duplicate);
}
}

But this just increments the count by one everytime ANY duplicate is found, I have no idea how to pick the highest occurance of a number out

Any help would be appreciated

Rachel  Reply With Quote

2. ## Re: Count occurances in array

You will need three variables:
a: the current count
b: the highest count so far
c: the value that has the highest count so far.

Then use 2 nested loops. Count how many times the first number occurs using a. Store the count in b and the number in c. Reset a to 0 and go around again counting the second number. If the count for the second number is higher than b then reassign b and c. etc.

Note: use better variable names than a b and c.  Reply With Quote

3. Member Join Date
Nov 2012
Posts
2
Rep Power
0

## Re: Count occurances in array

Can someone just confirm that this is right to count and store the number?

Java Code:
```if (a[i] == a[j]) {
value = a[i];
if (value == a[j]) {
count++;
duplicate = count;
}
}
count = 1;```
Thank you, I think I'm just not getting something here :(

EDIT: Ok for some reason it's counting everything past the second occurance as that number
eg. if I type in 3 4 3 5 6 it'll give me a count of 4 instead of 2 =/
Last edited by quad64bit; 11-09-2012 at 05:45 PM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•