英文:
Can I convert for loop number pattern to while loop and do while loop?
问题
以下是您提供的代码的翻译结果:
使用for循环打印数字"1"图案的代码如下:
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循环打印数字"1"图案的代码如下:
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++;
}
英文:
I'm learning java looping, and managed to print a number one pattern using the for loop.
I tried printing the number one pattern using the while and do while loop, but had difficulty. This is my code:
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();
}
This is my while loop code:
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++;
}
答案1
得分: 1
是的,任何for
循环都可以转换为while
或do-while
循环。
例如:
for (初始化; 条件检查; 语句1) {
// ......
}
这里的 语句1
=> 通常是在条件检查中使用的变量的 增量
或 减量
同样的等效 while
循环为:
初始化;
while (条件检查) {
// .......
语句1;
}
所以看起来你忘记初始化其中一个变量。另一个回答已经给了你那部分内容。
这个回答会帮助你将 for
循环映射到 while
循环,反之亦然。
希望能有所帮助。
英文:
Yes, any for loop can be converted into a while or do-while.
For example:
for(initialize; condition_check, statement1) {
......
}
Here statement1
=> generally this is an increment
or decrement
of a variable used in the condition_check
Similarly the equivalent while loop would be:
initialize;
while (condition_check) {
.......;
statement1;
}
So it seems that you have forgotten to initialize one of the variables. The other answer has already given you that.
This answer would help in mapping the for
loop to the while
loop and vice-versa.
Hope it helps.
答案2
得分: 1
需要在第一个 `j_while` 结束后重置 `j` 计数器
int i = 0, j = 0;
while (i <= 7)
{
// 也可以在这里重置
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++;
}
英文:
Need to reset j
counter after first j_while
end
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++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论