简体   繁体   English

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

[英]How do I translate a foreach c# 2d array loop to java

I have this piece of C# code that I need to re-write in java. 我有这段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();
            }
        }
}

So far my java code looks like this: 到目前为止,我的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();
               }
            }
        }
}

I am stuck at after CellCondition[][] condition = currentCondition[i][j]; 我陷入了CellCondition[][] condition = currentCondition[i][j]; line and I am not sure if the looping was done correctly either. 我不确定循环是否正确完成。 Any advise would be grateful. 任何建议都会感激不尽。

In your case it seems like you're not really interested in knowing what the index is for each of the CellCondition objects. 在你的情况下,你似乎并不真正想知道每个CellCondition对象的索引是什么。 Therefore you couldve used the java equivalent of a foreach loop: 因此,你可以使用foreach循环的java等价物:

for (CellCondition[] a : currentCondition)
{
    for (CellCondition b : a)
    {
        //Do whatever with b
    }
}
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();
            }
        }
    }
}

Just access the cell. 只需访问单元格。 Each cell is a CellCondition , not a CellCondition[][] . 每个单元格都是CellCondition ,而不是CellCondition[][]

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

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