Help with arrays!

Discussion in 'Java' started by Hero89, Jan 15, 2010.

  1. Hero89

    Hero89 New Member

    Joined:
    Jan 15, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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?
     
  2. ewaldhorn

    ewaldhorn New Member

    Joined:
    Feb 16, 2010
    Messages:
    36
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    Cape Town, South Africa
    Home Page:
    http://www.javak.co.za
    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
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice