Can a for loop be written to create an infinite lo

2020-04-04 11:03发布

Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?

标签: java for-loop
12条回答
女痞
2楼-- · 2020-04-04 11:19

Ofcourse for loops can cause infinite loops. An example is:

for(int i = 0; i < 99; i /= 2){ ... }

Because i is never incremented, it will stay in the body of the for loop forever until you quit the program.

查看更多
甜甜的少女心
3楼-- · 2020-04-04 11:23

Sure you can

for(int i = 0; i == i; i++) {}

Any loop can be made infinite as long as you make a way to never hit the exit conditions.

查看更多
唯我独甜
4楼-- · 2020-04-04 11:23

Dont forget mistakes like

for (int i=0; i<30; i++)
{
    //code
   i--;
}

It's not as uncommon as it should be.

查看更多
老娘就宠你
5楼-- · 2020-04-04 11:24
for(;;){}

is same as

while(true){}
查看更多
forever°为你锁心
6楼-- · 2020-04-04 11:24

Apart from issues of scope and one other thing, this:

for(<init>; <test>; <step>) {
  <body>
}

is the same as:

<init>
while(<test>) {
  <body>
  <step>
}

As other people have alluded to, in the same way that you can have a while loop without an <init> form or <step> form, you can have a for loop without them:

while(<test>) {
  <body>
}

is the same as

for(;<test>;) {
  <body>
} //Although this is terrible style

And finally, you could have a

for(;true;) {
  <body>
}

Now, remember when I said there was one other thing? It's that for loops don't need a test--yielding the solution everyone else has posted:

for(;;) {
  <body>
}
查看更多
我只想做你的唯一
7楼-- · 2020-04-04 11:26

There's lots of ways to make for loops infinite. This is the solution I found:

int j = 1;
for (int i = 0; i < j; i++) {
  //insert code here
  j++;
}

This works really well for me because it allows the loop to check an infinite amount of values as well as looping infinitely.

查看更多
登录 后发表回答