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
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.
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");
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With