Search code examples
javaif-statementwhile-loopjgrasp

I need to get two separate lines for evens and odds, but the catch is, I can use only one while loop


This is my code:

int numb = 50;
int odd;
int even;
while (numb <= 100) {
    if (numb % 2 == 0) {
        even = numb;
        System.out.println(even);
        System.out.print(", ");
        numb++;
    }
    System.out.println("");
    if (numb % 2 != 0) {
        odd = numb;
        System.out.print(odd);
        System.out.print(", ");
        numb++;
    }
}

So far, it prints two columns of answers but i need to separate rows of evens and odds. What am I doing wrong?


Solution

  • You can use two StringBuilder and keep appending sOdd and sEven to respective StringBuilder and after the loop you can print them.

    Something similar

    StringBuilder sOdd = new StringBuilder("");
    StringBuilder sEven = new StringBuilder("");
    
    while (numb <= 100) {
        if (numb % 2 == 0) {
            sEven.append(numb).append(",");
        }
        if (numb % 2 != 0) {
            sOdd.append(numb).append(",");
        }
       numb++;
    }
    
    System.out.println(sEven.toString()+"\n"+sOdd.toString());