【问题标题】:loop through sections of an array循环遍历数组的各个部分
【发布时间】:2020-05-04 01:22:34
【问题描述】:

正在寻找我是否可以在遇到问题时获得一些帮助。所以我目前正在尝试遍历二维数组的各个部分,但不确定该怎么做。

基本上我将拥有一个 4x4 或 9x9 或 25x25 的数组,并且我需要能够迭代块并检查重复项。

例如 4x4,我将迭代 4 个 2x2 数组。 9x9 将是 9 个 3x3 数组等。

尝试了一段时间,但没有成功 这个我试过了

任何帮助都会很棒, 干杯

【问题讨论】:

  • 请编辑您的问题并添加您迄今为止尝试过的内容。
  • 你的问题需要更清楚,你做了什么。我可以找到很多使用关键字“java for loop 2d array”的指令

标签: java arrays loops


【解决方案1】:

如果数组总是二维的,那么你可以这样做:

import java.util.ArrayList;
import java.util.List;

class Main {
  public static void main(String[] args) {

      // Initialize the 2d array
      int size = 3;
      int[][] table = new int[size][size];
      for (int row = 0; row < size; row ++)
          for (int col = 0; col < size; col++)
              table[row][col] = (int) (20.0 * Math.random());

      // Scan for duplicates
      List seen = new ArrayList();
      List duplicates = new ArrayList();

      for (int row = 0; row < size; row ++) {
          for (int col = 0; col < size; col++) {
            boolean exists = seen.contains(table[row][col]);
            if (!exists) {
              seen.add(table[row][col]);
              continue;
            }
            duplicates.add(table[row][col]);
          }
      }

      System.out.println(seen);
      System.out.println (duplicates);
  }
}

【讨论】:

  • 抱歉,没有澄清,但丹,您的回答非常有效,谢谢!
  • 没问题!感谢您接受答案。介意也给它一个赞成票吗?
猜你喜欢
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 2011-06-27
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多