简体   繁体   English

使用嵌套的for循环初始化2D数组并查找模式

[英]Initialize 2D array using nested for loops and finding a pattern

I'm trying to figure out how nested for loops for initializing variables work. 我试图弄清楚嵌套变量的初始化循环是如何工作的。 I looked at another question on here that initialized values in a 2D array from 1 to 15 which seemed reasonable using the code: 我在这里看到了另一个问题,该问题在从1到15的2D数组中初始化了值,使用代码似乎合理:

 for (int i = 0; i < row.length; i++) {
        for (int j = 0; j < row[0].length; j++) {
            row[i][j] = (i * row[0].length) + j;
        }
    }

I'm trying to extend that idea so that another array has the pattern as follows: 我正在尝试扩展该想法,以便另一个数组具有如下模式:

 {0, 9,18,27,36,45,54,63,72} //row0...row8
 { 1,10,19,28,37,46,55,64,73}

It obvious that once a row completes a number is incremented by 1 and you keep adding 9 until you get to the end of the row. 很明显,一旦完成一行,数字就会增加1,并且您一直加9直到到达行末。 How is this represented in code? 这在代码中如何表示? Solution to this problem would be great but a more general approach would be appreciated more if possible. 解决这个问题的方法很棒,但是,如果可能的话,更一般的方法将受到更多的赞赏。 My guess is that the headings for the for loop statements don't change but rather its the assignment equation that does. 我的猜测是for循环语句的标题不会更改,而是其分配方程式会更改。

Would this work? 这行得通吗?

for(int i=0; i < 9; i++){
  for(int j=0; j < 9; j++){
    row[i][j] = j+i;
  }
}
for (int i = 0; i < row.length; i++) {
    for (int j = 0; j < row[j].length; j++) {
        row[i][j] = i + j * 9;
    }
}

Have a try with the following code: 尝试以下代码:

    int[][] row = new int[9][9];
    for (int i = 0; i < row.length; i++) {
        row[i][0] = i;
        for (int j = 1; j < row[i].length; j++) {
            row[i][j] = row[i][j - 1] + 9;
        }
    }

    /*
     * Print 2d-array
     */

    for (int i = 0; i < row.length; i++) {
        for (int j = 0; j < row[i].length; j++) {
            System.out.printf("%2d ", row[i][j]);
        }
        System.out.println();
    }

Output in Console: 在控制台中输出:

 0  9 18 27 36 45 54 63 72 
 1 10 19 28 37 46 55 64 73 
 2 11 20 29 38 47 56 65 74 
 3 12 21 30 39 48 57 66 75 
 4 13 22 31 40 49 58 67 76 
 5 14 23 32 41 50 59 68 77 
 6 15 24 33 42 51 60 69 78 
 7 16 25 34 43 52 61 70 79 
 8 17 26 35 44 53 62 71 80 

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

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