如何将foreach c#2d数组循环转换为java

时间:2015-07-31 17:12:46

标签: java c# arrays

我有一段C#代码需要在java中重写。

private static void ShowGrid(CellCondition[,] currentCondition)
{

        int x = 0;
        int rowLength =5;

        foreach (var condition in currentCondition)
        {
            var output = condition == CellCondition.Alive ? "O" : "·";
            Console.Write(output);
            x++;
           if (x >= rowLength)
            {
                x = 0;
                Console.WriteLine();
            }
        }
}

到目前为止,我的java代码如下所示:

private static void ShowGrid(CellCondition[][] currentCondition) {

        int x = 0;
        int rowLength = 5;

        for(int i=0;i<currentCondition.length;i++){
            for(int j =0; j<currentCondition[0].length;j++){
                CellCondition[][] condition = currentCondition[i][j];
                //I am stuck at here
                x++;
            if(x>=rowLength){
               x=0; 
               System.out.println();
               }
            }
        }
}

我被困在CellCondition[][] condition = currentCondition[i][j];行之后,我不确定循环是否也正确完成。任何建议都会很感激。

2 个答案:

答案 0 :(得分:2)

在你的情况下,你似乎并不真正想知道每个CellCondition对象的索引是什么。因此,你可以使用foreach循环的java等价物:

for (CellCondition[] a : currentCondition)
{
    for (CellCondition b : a)
    {
        //Do whatever with b
    }
}

答案 1 :(得分:1)

private static void ShowGrid(CellCondition[][] currentCondition) {
    int x = 0;
    int rowLength = 5;

    for(int i = 0; i < currentCondition.length; i++) {
        for(int j = 0; j < currentCondition[0].length; j++) {
            CellCondition condition = currentCondition[i][j];
            String output = (condition == CellCondition.Alive ? "O" : "·");
            System.out.print(output);
            x++;
            if(x >= rowLength) {
               x = 0; 
               System.out.println();
            }
        }
    }
}

只需访问该单元格即可。每个单元格都是CellCondition,而不是CellCondition[][]