+ 3
Can someone pls explain this code to me. While does it print an infinite loop of 4.
public class Program { public static void main(String[] args) { int x = 1; while(x < 5) { System.out.println(x); if(x == 4) { continue ; } x++; } } }
4 Réponses
+ 4
It's an infinite loop. It displays 1, 2, 3 and then as many as possible 4s. This is because the 'if(x == 4)' condition will be true when x is 4 then it continues meaning it stops the current iteration and loops again avoiding the 'x++' which would stop the infinite loop from happening.
+ 7
We declare an int variable x, value 1;
While 5 is greater than x, print x.
+ 2
Thanks
+ 2
When the x value is 4, the continue statement says to go to the next iteration and because there is no an increment to the x, through the x++, then the 4 <5 condition will be true and an infinite loop of 4.