Not able to understand the issue with the below code block.
numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);
Getting error: not a statement.
Not able to understand the issue with the below code block.
numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);
Getting error: not a statement.
You cannot use a ternary operator in a statement context. It is only allowed as an expression. You have two options:
Use an if statement:
if (numArray[i] % 2 == 1) {
oddList.add(numArray[i]);
} else {
evenList.add(numArray[i]);
}
Restructure the ternary operator (does not work in general, but removes some duplication in this case):
(numArray[i] % 2 == 1 ? oddList : evenList).add(numArray[i]);
In addition to previous comment. Java program consists of statements. In you case numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]); is part of ConditionalExpression.
ConditionalExpression must be part same statement for example Assigment or ReturnStatement.
Thus you can use this, because List.add() returns boolean value:
Assigment boolean b = numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);
Return
return numArray[i] % 2 == 1 ? oddList.add(numArray[i]) : evenList.add(numArray[i]);
Another statement with boolean value...