If statement nested in for loop

Tags:



I’m trying to create a program that prints “-” if the number is divisible by 2 and “*” if it is not. I get it to print the numbers, – and *, but it is not printing – and * in place of the number, if that makes sense?

public class Exercise2 {
    public static void main(String[] args) {
        for(int i = 100; i <= 200; i++) {
            if(i % 2 == 0){
                System.out.println("-");
            } else {
                System.out.println("*");
            }
            System.out.println(i);
        }
    }

}

I can’t understand where exactly I’m going wrong. Any help is appreciated and thank you in advance.

Answer

If you dont want to print the numbers you can just remove System.out.println(i); from your original answer and it should work fine.

If you want to print the symbol and the number in the same line it can be done by changing the System.out.println() to System.out.print().

public class Exercise2 {
    public static void main(String[] args) {
        for(int i = 100; i <= 200; i++) {
            if(i % 2 == 0){
                System.out.print("- ");
            } else {
                System.out.print("* ");
            }
            System.out.println(i);
        }
    }
}

The answer above will print the numbers in this fassion:

- 100
* 101
- 102
* 103
- 104
* 105
- 106
...


Source: stackoverflow