通过二维数组迭代 [英] Iterate through 2 dimensional array

查看:150
本文介绍了通过二维数组迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接四板,我用二维数组模拟(数组[x] [y] x = x坐标,y = y坐标)。我必须使用System.out.println,所以我必须遍历行。

I have a "connect four board" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use "System.out.println", so I have to iterate through the rows.

我需要一种迭代这种方式的方法[0,0] [ 1,0] [2,0] [3,0] [0,1] [1,1] [2,1]等

I need a way to iterate this way [0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1] etc

如果我使用正常过程:

for (int i = 0; i<array.length; i++){
     for (int j = 0; j<array[i].length; j++){
        string += array[i][j];
     } System.out.println(string)

}

它不起作用,因为它以这种方式迭代[0,0] [0,1] [0,2] [0,3]等

it doesnt work because it iterates this way [0,0] [0,1] [0,2] [0,3] etc

正常程序保持不变x并递增y直到列的结尾,但我需要在y中说并递增x直到行的结尾。

The normal procedure stays in x and increments y until the end of the column, but i need to say in y and increment x until the end of the row.

推荐答案

将它视为一个数组数组,这肯定会起作用。

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

这篇关于通过二维数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆