我正在编写扫雷程序——我已经完成了,但现在我的任务发生了变化。我无法使用 If-Else
或 Switch
。您对如何重写此代码片段有什么建议吗?
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
if (bombs[i][j])
System.out.print("* ");
else
System.out.print(". ");
System.out.println();
}
}
最佳答案
您可以使用三元运算符:
String result = (bombs[i][j]) ? "* " : ". ";
System.out.println(result);
您还可以在其中添加一个 while
循环:
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
while (bombs[i][j]) { System.out.print("* "); break; } //Will execute once if the statement holds
while (!bombs[i][j]) { System.out.print(". "); break; } // Same here.
System.out.println();
}
关于java - 无条件编程 - 不能使用 If、Else 或 Switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32784365/