Do {} while ( , ) with comma operator, is that even possible?

1k views Asked by At

Yesterday I read about the comma operator in Java for for-loops. Which worked as I expected them to. I thought of this construction but it does not work as expected.

';' expected
        } while((userInput < 1 || userInput > 3), wrongInput = true);

';' expected
        } while((userInput < 1 || userInput > 3), wrongInput = true);

My idea was that after one iteration, if the userInput was not between 1 and 3, it should set boolean wrongInput to true so that during the next iteration an error message will be displayed. Indicating that the userInput was invalid.

private int askUserToSelectDifficulty() {
    int userInput;
    Boolean wrongInput = false;

    do{
        if(wrongInput) println("\n\t Wrong input: possible selection 1, 2 or 3");
        userInput = readInt();
    } while((userInput < 1 || userInput > 3), wrongInput = true);

    return userInput;
}

I imagine that maybe because this is inside the equivalent to the conditional part of a for-loop, that this is invalid syntax. Because you can't use a comma operator in the conditional part?

Examples of where I have seen the comma operator being used in for-loops: Giving multiple conditions in for loop in Java Java - comma operator outside for loop declaration

2

There are 2 answers

0
NPE On BEST ANSWER

There is no comma operator in Java (not in the C/C++ sense anyway). There are some contexts where you can declare and initialise multiple things at once using a comma, but that doesn't generalise to other contexts, like the one in your example.

One way to phrase your loop is like so:

while (true) {
    userInput = readInt();
    if (userInput >= 1 && userInput <= 3) {
        break;
    }
    println("\n\t Wrong input: possible selection 1, 2 or 3");
};
0
Peter Lawrey On

It might be best to unroll this a little.

userInput = readInt();
while (userInput < 1 || userInput > 3) {
    System.out.println("\n\tWrong input: possible selection 1, 2 or 3");
    userInput = readInt();
}

This avoids the need for a flag.