3

I have a 2 dimensional 9 x 9 array (twoArray) that is filled with numbers between 1 & 17.
I am trying to create a one dimensional array (oneArray) that will provide me with the occurrence of the numbers in twoArray.

i.e. if the number ‘1’ appears ‘3’ times in the twoArray, then the value in oneArray[0] will be ‘3’, the number ‘15’ once, then oneArray[14] will be ‘1’, etc. I have the following code that I have written, but I am getting a ‘ArrayIndexOutOfBoundsException’

Not sure if my code is even correct for accomplishing this. Any guidance would be appreciated. I am not looking for the answer, just some advice so I can do it myself.

int[] oneArray= new int[17];
for (int i= 0; i< twoArray.length; i++)
{
    for (int j= 0; j< twoArray[j].length; j++) **// exception occurs here**
    {
        int num = 0;
        num = twoArray[i][j] - 1;
        oneArray[num] += 1;
    }
}

2 Answers 2

5

You have a typo: the condition should be j< twoArray[i].length, not j< twoArray[j].length. The rest of the program should work, but you may consider changing a couple of really small things:

  • Consider combining initialization of num with its calculation
  • Consider using ++ in place of += 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Don't know how I missed that!
4

You need

for (int j= 0; j< twoArray[i].length; j++)
                           ^--i here, and not j

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.