Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Is there a limit to how many levels you can nest i
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
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 thefor
loop forever until you quit the program.Sure you can
Any loop can be made infinite as long as you make a way to never hit the exit conditions.
Dont forget mistakes like
It's not as uncommon as it should be.
is same as
Apart from issues of scope and one other thing, this:
is the same as:
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 afor
loop without them:is the same as
And finally, you could have a
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:There's lots of ways to make for loops infinite. This is the solution I found:
This works really well for me because it allows the loop to check an infinite amount of values as well as looping infinitely.