arnbobo arnbobo - 18 days ago 4x
Java Question

Counting number of times an int occurs in an array (Java)

I'm trying to count the number of occurences of

s, one to six inclusive, in an array of size 6. I want to return an array with the number of times an int appears in each index, but with one at index zero.



Expected output: [2,1,2,1,1,0].

However, it outputs [1,1,3,0,1,0] with the code excerpt below. How can I fix this? I can't find where I'm going wrong.

public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
return amt;

public int[] countNumOfEachScore(){
int[] scores = new int[6];
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
scores[i] = dice[i].getValue();
for (int j = 0; j < 6; j++){
counts[j] = arrayCount(scores, j+1);
return counts;

dice[] is just an array of Die objects, which have a method getValue() which returns an int between 1 and 6, inclusive. counts[] is the int array with the wrong contents.


It'll be faster to write another code instead of debugging yours.

public static int[] count(int[] array) {
    int[] result = new int[6];
    for (int i = 0; i < array.length; i++) {
        } catch (IndexOutOfBoundsException e) {
            throw new IllegalArgumentException("The numbers must be between 1 and 6. Was " + String.valueOf(array[i]));
    return result;

The above will result in an array of 6 ints. ith number in the result array will store the number of occurences of i+1.

PoC for the OP
enter image description here