无法在二维数组内比较两个值。

huangapple go评论143阅读模式
英文:

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&lt;arr.length;j++)
{
	for(k=0;k&lt;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&lt;arr[j].length-1. But I am not sure what you actually what to achieve with the code.

huangapple
  • 本文由 发表于 2020年5月3日 22:55:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61576541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定