• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java programming problem

kami333

Diamond Member
Grrr, I just can't figure out how to get this to work properly. Basically I have an array of numbers sorted from lowest to highest and I need to count how many of a certain number there are. What I have:

public static void numberCount(int[]a, int n){
int l,j,k;
k=1;
System.out.println("N\t\tCount");
for (l=0; l<n-1; l++){
j=l+1;
if (a[l]==a[j]){
k++;
}
else{
System.out.println(a[l]+"\t\t"+k);
k=1;
}
}
}

It works great, to a point. Problem is that it won't display the last number in the array and its count because a[j] ends up bigger than the array I have and it won't run that part. Any suggestions?
 
Just figured it out, added System.out.println(a[l]+"\t\t"+k); after the for () loop and now it works, got the last array value and count that I needed.
 
I'm a little confused about what's what, but here's what I'm thinking:

If n is the length of the array and your exit condition is i<n-1, you will always miss the last piece of the array
If you have 5 elements in the array, the indices are 0-4. When i is 4, it will not be < 4, so you'll miss that last element.

Your exit condition should be i<=n-1 or i < n

 
Back
Top