英文:
Unable to compare two values within the 2D array
问题
我正在解决一个问题,需要在二维数组中比较两个值,但是我无法得到输出。请帮助我解决这个问题。这是我的代码片段:
int arr[][] = new int[N][N];
for (j = 0; j < arr.length; j++) {
for (k = 0; k < arr[j].length - 1; k++) {
if (arr[j][k] == arr[j][k + 1])
c++;
}
}
英文:
I am working on a problem in which I have to compare two values within the 2D array but I am unable to get the output. Kindly help me to come out of this problem. Here's a glimpse of my code:
int arr[][]=new int[N][N];
for(j=0;j<arr.length;j++)
{
for(k=0;k<arr[j].length;k++)
{
if(arr[j][k]==arr[j][k+1])
c++;
}
}
答案1
得分: 1
问题是,由于比较if(arr[j][k]==arr[j][k+1])
,你会得到一个ArrayOutOfBoundsException(数组越界异常)。这会在你到达数组的最后一个元素时发生,因为当k严格小于arr[j].length
时,k+1元素是不存在的。
也许你想将条件改为k<arr[j].length-1
。但我不确定你实际想要通过这段代码实现什么。
英文:
The problem is that you will get an ArrayOutOfBoundsException due to the comparison if(arr[j][k]==arr[j][k+1])
. This happens when you reach the last element of the array since when k is strictly less than arr[j].length
, then k+1 element doesn't exist.
Maybe you want to change the condition to k<arr[j].length-1
. But I am not sure what you actually what to achieve with the code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论