我正在学习Java循环,并设法使用for循环打印了一个数字模式。我尝试使用while和while循环打印第一模式,但遇到了困难。这是我的代码:
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 4; j++) {
if ((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
System.out.print("1");
else
System.out.print(" ");
}
System.out.println();
}
这是我的while循环代码:
int i = 0, j = 0;
while (i <= 7) {
while (j <= 4) {
if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
System.out.print("1");
else
System.out.print(" ");
j++;
}
System.out.println();
i++;
}
是的,任何for循环都可以转换为while或do-while。
例如:
for(initialize; condition_check, statement1) {
......
}
这里statement1
=>通常,这是在condition_check中使用的变量的increment
或decrement
类似的while循环将是:
initialize;
while (condition_check) {
.......;
statement1;
}
希望有帮助。
在第一个j
结束后需要重置j_while
计数器
int i = 0, j = 0;
while (i <= 7)
{
//could also reset here
j=0;
while (j <= 4)
{
if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
System.out.print("1");
else
System.out.print(" ");
j++;
}
System.out.println();
i++;
}