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:28

Just for fun (and this too long for a comment): a lot of people will be very surprised to learn that for a lot of very practical purposes the following is nearly an infinite loop:

    for (long i = Long.MIN_VALUE; i < Long.MAX_VALUE; i++) {
        ...
    }

If the thread executing this loops can do 4 billions cycles per second and can do the increment and the check in one cycle (quite beefy for a single thread) and if my maths ain't totally off, I think the above code needs about 150 years to execute : )

查看更多
虎瘦雄心在
3楼-- · 2020-04-04 11:28

There is also this one, to complete the topic:

do {something();} while(true);
查看更多
▲ chillily
4楼-- · 2020-04-04 11:36

The way I made my server to run as long until I shut it down is

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

查看更多
迷人小祖宗
5楼-- · 2020-04-04 11:38

You can also do such with for loops. E.g. the following is identical to while(true):

for(;;) {
}
查看更多
仙女界的扛把子
6楼-- · 2020-04-04 11:38

I'll just add this since nobody did this version:

for(;;);
查看更多
萌系小妹纸
7楼-- · 2020-04-04 11:39

you can declare a subpart of the code to be another part in a for loop, example -

public class (classname) {
    for(int i = 1; i <= 4; i++) {
        for(int j = 1; i <= 4; j++) {
    system.out.println(i + "*" + j + "=" (i*j));
}

}

it is almost in infinite loop; if you change int to long, and add more variables, you can practically make it last 25 x 10^12 minutes long

查看更多
登录 后发表回答