1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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:
    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