How do I break correctly

Question from Quadzilla#9639

public class Pyramid {

    public static void main(String[] args) {
        
        int s = 50;
        while (true) {
            s += 50;
            if (s > 50) {
                System.out.println(s);
            } else {
                s = 200;
                break;
            }
            while (s >= 200) {
                break;
            }
        }
    }
}

How can I add in a break to prevent the numbers from going to 20,000 in the terminal and beyond. Am I applying break correctly? I adapted the code from a java forum that printed a pyramid & thought today is the day to apply the break statement. s was changed by me to integer rather than string.

So first

        int s = 50;
        while (true) {
            s += 50;
            if (s > 50) {
                System.out.println(s);
            } else {
                s = 200;
                break;
            }
            while (s >= 200) {
                break;
            }
        }

This else block here where you set s to 200 will never run.

s starts out at 50, you immediately add 50 to it, So it's always above 50 and you never set it to anything lower.

        int s = 50;
        while (true) {
            s += 50;
            if (s > 50) {
                System.out.println(s);
            } 

            while (s >= 200) {
                break;
            }
        }

Now for that last while block with the break.

break is a "terminal" action. You will exit your loop if you do it. And because you nest that other loop you only break out of the while (s >= 200) loop, not the while (true) loop.

So what you want isn't a while, it's an if.

        int s = 50;
        while (true) {
            s += 50;
            if (s > 50) {
                System.out.println(s);
            } 

            if (s >= 200) {
                break;
            }
        }

<- Index