I'm fairly new to Java data-structures and I need some assistance to have multiple conditions using ternary operator or if there's much better approach on what I'm trying to do.
Basically, I have a text file that put into a 2D array and splitting each line character by character.
However, I'm having some trouble with conditional statement to check specific characters from the line.
Here's my current algorithm to do that.
for (int i = 2; i < lines.size() - 1; i++) {
String floorLine = lines.get(i);
int j = 0;
for(char coor : floorLine.toCharArray()) {
floor[i - 2][j] = (coor == '#') ? 0 : 1;
}
}
As of now, I'm only checking if there's # in line then it will encode as 0 else 1. However, I would like to have something like this
floor[i-2][j] = (coor == '#') ? 0 floor[i-2][j] = (coor == 'X') ? 1 floor[i-2][j] = (coor == 'Z') ? 2 : 3
So if I use the normal if else statement, I should have like this
if 2d array == ( coor == '#') encode as 0
if 2d array == ( coor == 'X') encode as 1
if 2d array == ( coor == 'Z') encode as 2
else encode as 3
Any suggestions or tips will be appreciated! Thank you in advance.
The form of the conditional expression is:
condition? value_if_true : value_if_false
When they're chained, it looks like this:
condition_1 ? value_if_1 : condition_2 ? value_if_2 : value_otherwise
So I think you mean:
floor[i-2][j] = (coor=='#' ? 0 : coor=='X' ? 1 : coor=='Z' ? 2 : 3);
To me, this is simple enough to be perfectly readable, but lots of people argue against this use of conditional operator like this; and if it were any more complicated you would be better off using if
statements instead.
Java is in the process of introducing switch expressions, which would also work well for this case.