Do {} while (,) with a comma operator - is this possible?

Yesterday I read about the comma in Java for for-loops. It worked as I expected. I thought about this design, 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 userInput not between 1 and 3, it should set boolean wrongInput to true so that an error message is displayed during the next iteration. Indicates that userInput not valid.

 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 assume that, possibly because it is inside the equivalent of the conditional part of the for loop, this is not valid syntax. Because you cannot use the comma operator in the conditional part?

Examples of where I saw the comma operator used in for-loops: Providing multiple conditions for a loop in Java Java - comma operator for loop declaration

+5
source share
2 answers

There is no comma operator in Java (but not in the sense of C / C ++). There are several contexts where you can declare and initialize several elements at once with a comma, but this does not generalize to other contexts, for example, in your example.

One way to express your loop:

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

It’s best to talk a little about it.

 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.

+3
source

Source: https://habr.com/ru/post/1207663/


All Articles