如何将foreach c#2d数组循环转换为java
本文关键字:循环 转换 java 数组 c#2d foreach | 更新日期: 2023-09-27 18:05:43
我有一段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[][]
。