java 使用 if 条件的 while 循环内的 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16473286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
for loop inside while loop using if condition
提问by Jessica M.
I'm a little bit confused about a homework assignment I'm working on. I'm trying to write 7 sets of 123. Except when the number of set is even I don't want to write 123 but just the word even and no numbers and move on to the next set.
Im using the while loop to keep track of counting the sets and the for loop to do the counting 123. But the problem is as the program is written it just prints even continuously.
I tried putting the if condition inside the for loop but that only continuously prints (123 even) forever.
Am i incorrectly applying the if condition? Am I incorrectly applying the for condition?
我对我正在做的家庭作业有点困惑。我正在尝试写 7 组 123。除非组数是偶数,否则我不想写 123 而只是单词偶数,没有数字,然后继续下一组。
我使用 while 循环来跟踪对集合的计数,并使用 for 循环来进行计数 123。但问题是在编写程序时它只是连续打印。
我尝试将 if 条件放在 for 循环中,但它只会永远连续打印(甚至 123)。
我是否错误地应用了 if 条件?我是否错误地应用了 for 条件?
import acm.program.*;
public class TestProgram extends ConsoleProgram
{
public void run()
{
int i = 1;
while (i <= 7)
{
if (i % 2 == 0)
{
println("even");
}
else
{
for (int j = 1; j <= 3; j++)
{
println(j);
}
}
}
}
}
回答by jongusmoe
You're not incrementing i at all, so it'll never terminate. After your for statement, add something like
你根本没有增加 i ,所以它永远不会终止。在您的 for 语句之后,添加类似
i++;
回答by rgettman
What you have written is an infinite loop because i
will always be less than or equal to 7. It is intialized to 1
and you do nothing to change it.
你写的是一个无限循环,因为它i
总是小于或等于 7。它被初始化为1
并且你没有做任何事情来改变它。