5

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

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Joop
  • 3,706
  • 34
  • 55
  • 1
    take a look at java operators - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – Joseph118 Nov 25 '14 at 11:56
  • 1
    and those examples of coma are being used to assign multiple values BUT not conditions – Joseph118 Nov 25 '14 at 11:57
  • @Joseph118 Good to know that the , is not an operator in Java at all as NPE already pointed out. It is indeed not in the documentation. – Joop Nov 25 '14 at 12:06

2 Answers2

4

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

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");
};
NPE
  • 486,780
  • 108
  • 951
  • 1,012