Search code examples
javaloopsbreakinfinitecontinue

while (1) loop with continue and break statements


I need help with a while(1) loop that contains a continue and break statement. It must count from numbers 1 to 20 and for every even number, it must output the values. I have to use a continue after my writeToPage statement and use a break statement when it reaches 20. This is what I tested out but the file will not even load:

writeToPage("Program 4: Continue and Break");
writeToPage("");

while(1) {
    if (i % 2 == 0){
        writeToPage(+ i);
        continue;
    }
    if (i >= 20){
        break;
    }
}

I'm not sure if I'm putting them in the wrong place.


Solution

    1. For infinite loop, you need to write while(true) instead of while(1).
    2. If i % 2 != 0 is true, simply increment i by 1 and continue; otherwise, print the value of i and increment i by 1.

    Demo:

    public class Main {
        public static void main(String[] args) {
            int i = 1;
            while (true) {
                if (i % 2 != 0) {
                    i++;
                    continue;
                } else {
                    writeToPage(i);
                    i++;
                }
    
                if (i >= 20) {
                    break;
                }
            }
        }
    
        static void writeToPage(int i) {
            System.out.println(i);
        }
    }
    

    Output:

    2
    4
    6
    8
    10
    12
    14
    16
    18
    20