首页 > 解决方案 > 处理二维整数数组的行

问题描述

在此先感谢您的帮助。我是 Java 新手,在处理 2D 整数数组的行时遇到了困难。我已经搜索了这个论坛和其他资源丰富的地方,但没有任何帮助。

以下是数组元素

1 2 3 4

4 9 17 26

2 4 6 8

1 3 5 7

9 12 32 33

4 8 10 16

3 7 9 21

10 11 12 13

这是我的错误代码:

for (int row=0; row<list.length; row++) {
    for (int col=0; col<list[row].length; col++) {
        if (list[row][0] + 1 != list[row][1] && 
                list[row][1] + 1 != list[row][2] &&
                list[row][2] + 1 != list[row][3]) {

            System.out.print(list[row][col] + " ");
        }

    }
    System.out.println()

假设您不知道数组元素的值,我需要一个代码来测试和打印其元素不连续递增 1 的数组行,例如 1 2 3 4 和 10 11 12 13。

标签: javaarrays

解决方案


您可以遍历整个列,比较每个值,并使用布尔值来跟踪它们是否连续递增。像这样的东西:

boolean rowIsConsecutive;
int previousValue;

for (int row = 0; row<list.length; row++) 
{
  rowIsConsecutive = true;
  previousValue = list[row][0]; // This will blow up with a 1D array. Just wrote it like this for readability. 

  for (int col = 1; col<list[row].length && rowIsConsecutive; col++) 
  {
    if (list[row][col] == previousValue + 1) 
    {
      previousValue = list[row][col];
    }
    else 
    {
      rowIsConsecutive = false;
    }
  }

  if (rowIsConsecutive)
  {
    System.out.println(Arrays.toString(list[row]));
  }
}

免责声明:我没有对此进行测试,但是这些方面的东西应该可以工作。我把它留给你想出一种更高效的方法来做到这一点:)


推荐阅读