Joseph Joseph - 1 month ago 7
Java Question

Java modulo if statement

public class MyFirstProgram {
public static void main(String[] args) {
for (int i=1; i<100; i++) {
if (i%2 == 0); {
System.out.println(i);
} elif(i%2 == 1); {
System.out.println(i);
}
}
}
}


I'm coding in an online Java IDE and I can't figure out why this modulo won't work, I'm trying to print out all even numbers and then odd numbers up to 99.

I'm guessing it's syntax related but from what I've searched I can't quite see where I've gone wrong with how I've written the code. The error I get is "could not compile".

Answer

You want something like

public class MyFirstProgram {
    public static void main(String[] args) {
        for (int i = 1; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(i + " even");
            } else { // must be odd
                System.out.println(i + " odd");
            }
        }
    }
}

To print all even, then all odd, you can use two loops.

public class MyFirstProgram {
    public static void main(String[] args) {
        System.out.println("Even");
        for (int i = 2; i < 100; i += 2)
            System.out.println(i);

        System.out.println();
        System.out.println("Odd");
        for (int i = 1; i < 100; i += 2)
            System.out.println(i);
    }
}

I suggest using your IDE to format your code and you will pick up common syntax errors.

Comments