how to count occurance of numbers using java arrays
out put comes from this program is:
1 occurs 1 times
13 occurs 1 times
0 occurs 2 times
9 occurs 0 times
84 occurs 1 times
0 occurs 2 times
13 occurs 3 times
2 occurs 1 times
instead of:
1 occurs 1 times
13 occurs 3 times
0 occurs 2 times
9 occurs 2 times
84 occurs 1 times
2 occurs 1 times
Code :
class occu{
public static void main(String arg[]){
int a[] = {1,13,0,9,9,84,0,13,13,2};
int i,j,count=0,temp,pretemp=-99999;
for(i=0;i<a.length;i++){
temp=a[i];
if(temp==pretemp)
continue;
else
for(j=0;j<a.length;j++)
if(a[j]==temp)
count++;
System.out.println( a[i]+ " OCCURS " +count+ " TIMES ");
count=0;
pretemp=a[i];
} // end for
} // end main
} // end class
Re: how to count occurance of numbers using java arrays
How does the program accumulate the total counts for each number that is found?
One problem I see with the code is missing {}s. You should always use {}s with loops and if statements to make sure you know what code goes in the loop or the if statement.
Also for debugging the Arrays class's toString() method is useful to see what is in an array:
Code :
System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));