Can a for loop be written to create an infinite loop or is it only while loops that do that?

前端 未结 12 1469
时光取名叫无心
时光取名叫无心 2021-01-17 23:58

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

相关标签:
12条回答
  • 2021-01-18 00:50

    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.

    0 讨论(0)
  • 2021-01-18 00:51

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

    0 讨论(0)
  • 2021-01-18 00:51

    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}

    0 讨论(0)
  • 2021-01-18 00:56

    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.

    0 讨论(0)
  • 2021-01-18 00:58

    There is also this one, to complete the topic:

    do {something();} while(true);
    
    0 讨论(0)
  • 2021-01-18 01:00

    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

    0 讨论(0)
提交回复
热议问题