簡體   English   中英

如何將foreach c#2d數組循環轉換為java

[英]How do I translate a foreach c# 2d array loop to 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();
            }
        }
}

到目前為止,我的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]; 我不確定循環是否正確完成。 任何建議都會感激不盡。

在你的情況下,你似乎並不真正想知道每個CellCondition對象的索引是什么。 因此,你可以使用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();
            }
        }
    }
}

只需訪問單元格。 每個單元格都是CellCondition ,而不是CellCondition[][]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM