简体   繁体   English

基于另一个数组递增数组中的值

[英]incrementing the values in an array based of another array

I have a 2 dimensional 9 x 9 array (twoArray) that is filled with numbers between 1 & 17. 我有一个2维9 x 9数组(twoArray),填充1到17之间的数字。
I am trying to create a one dimensional array (oneArray) that will provide me with the occurrence of the numbers in twoArray. 我正在尝试创建一个一维数组(oneArray),它将为我提供twoArray中数字的出现。

ie 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' 即如果数字'1'在twoArray中出现'3'次,则oneArray [0]中的值将为'3',数字'15'为一次,则oneArray [14]将为'1'等。我有以下代码,但我得到的是'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;
    }
}

You have a typo: the condition should be j< twoArray[i].length , not j< twoArray[j].length . 你有一个错字:条件应该是j< twoArray[i].length ,而不是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 考虑将num初始化与其计算相结合
  • Consider using ++ in place of += 1 考虑使用++代替+= 1

You need 你需要

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM