dwwilson66
dwwilson66

Reputation: 7074

How do I properly pass an array between methods

I'm having trouble passing an array between methods and have excerpted my code below.

I've successfully created two arrays, computerDice and humanDice, and now I need to count the number of ones, twos, threes, etc in each array. See example below the code. I've validated that a.) that the input arrays contain valid data and b.) the counter works properly.

However, now I'm trying to return occurences as an array--six distinct values of occurence representing ones, twos, threes, etc. in the array being SENT to the method--and have been unsuccessful. I keep having issues with my occurence return...incompatible types, bad operand typed for operand +...and I get something different with each thing I try. I'm obviously missing something with how to cast/populate this variable.

NOTE: This is homework; I'm just trying to grasp my conceptual mis-steps.

// SEND VALUES TO numToFind AND CREATE SCORING ARRAY FOR computerDice AND humanDice
        for(int i=1;i<7;i++)
        {
            int[] pipCountsComputer = findVals(computerDice,i);
            int[] pipCountsHuman = findVals(humanDice,i);
            System.out.println(i + " " + pipCountsComputer + " " + pipCountsHuman);
        }
    }
//
// COUNT INSTANCES OF numToFind IN arr[] AND RETURN THE occurence
    public static int[] findVals(int[] arr, int numToFind)
    {
        int[] occurence=0;
        for (int i = 0; i < arr.length; i++)
        {
            if (arr[i] == numToFind)
                occurence = occurence+1;
        }
        return occurence;
    }

I've already validated that, for example, given computerArray = 52334 and humanArray = 11163 my print statement yields:

1 0 3 (ones, computer has 0 ones, human has 3 ones)
2 1 0 (twos, computer has 1 two, human has 0 twos)
3 2 1 etc.
4 1 0 My desired arrays for this dataset would be:
5 1 0 pipCountsComputer{0,1,2,1,1,1}
6 0 1 pipCountsHuman{3,0,1,0,0,1}

Upvotes: 1

Views: 910

Answers (2)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236150

If I understood correctly, try this for counting the number of occurrences:

public static int findVals(int[] arr, int numToFind) {
    int occurence = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == numToFind)
            occurence++;
    }
    return occurence;
}

I really don't understand why you want to return an array, an occurrence is just a number.

Upvotes: 3

nickdos
nickdos

Reputation: 8414

As this smells like homework, I won't give you the answer but hint to it...

now I'm trying to return occurences as an array

You have not coded for this yet... look at the method signature again

public static void findVals(int[] arr, int numToFind)

Upvotes: 2

Related Questions