+ 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++; } } }

24th Mar 2018, 9:53 PM
The Programmer
The Programmer - avatar
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.
24th Mar 2018, 9:59 PM
TurtleShell
TurtleShell - avatar
+ 7
We declare an int variable x, value 1; While 5 is greater than x, print x.
24th Mar 2018, 9:57 PM
Chalza
Chalza - avatar
+ 2
Thanks
24th Mar 2018, 10:00 PM
The Programmer
The Programmer - avatar
+ 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.
25th Mar 2018, 3:47 AM
Billy Edson Burgoa Rosso
Billy Edson Burgoa Rosso - avatar