Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Help with arrays! (http://www.go4expert.com/forums/help-with-arrays-t20674/)

Hero89 16Jan2010 04:02

Help with arrays!
 
I need to make a code that will count all the instances of 1 number in an array. Here is what I have so far:

Code:


public class NumOccurrences
{
    public static int num (int[] a,int i)
    {
        int count = 0;
        a = new int [6];
        for (int j = 0; j < a.length; j++ )
        {
            if (a[0] == j)
                count++;
           
               
       
               
        }       
        return count;
               
        }
    }

2 out of my 5 tests pass, and I'm not sure what I am doing wrong, can someone point me in the right direction?

ewaldhorn 16Feb2010 16:34

Re: Help with arrays!
 
Hi.

In your code, you send two parameters to the num method, a[] and i.

I am going to assume that i is the number that needs to be tested for.

So...

In your code, make sure you check every number in the array by using j as the index for the array. Also, you should not create a again inside the method, as that would then remove the parameter passed to this object. I added a main method to make it easier to test the code. Running the example below, the output should be 3.

public class NumOccurrences
{
public static int num(int[] a, int i) {
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == i) {
count++;
}
}
return count;
}

public static void main(String[] args) {
int[] array = {5, 6, 4, 1, 6, 4, 5, 1, 2, 6, 8, 9};
System.out.println("Counted " + num(array, 6));
}
}


Best regards
Ewald


All times are GMT +5.5. The time now is 09:12.