Reputation: 27
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.
Upvotes: 1
Views: 5412
Reputation: 44130
May as well throw in how I would write this. Pull the conditional into a new method.
floor[i - 2][j] = getNumberForCoor(coor);
private static int getNumberForCoor(char coor) {
switch (coor) {
case '#': return 0;
case 'X': return 1;
case 'Z': return 2;
default: return 3;
}
}
Upvotes: 1
Reputation: 2373
Looks like you could put your replacements in a map.
static Map<Character, Integer> encodings = new HashMap<>();
static {
// static initializer, a way to populate the map easily, not the only way
encodings.put('#', 0);
encodings.put('X', 1);
encodings.put('Z', 2);
}
//and in your function
floor[i-2][j] = encodings.getOrDefault(coor, 3);
Upvotes: 0
Reputation: 109547
Besides the ternary expression chain I see two alternatives:
So
Map<Character, Integer> map = new HashMap<>();
map.put('#', 0);
map.put('X', 1);
map.put('!', 2);
String enc = "#X!";
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
: coor == 'X' ? 1
: coor == '!' ? 2
: 3;
floor[i - 2][j] = map.getOrDefault(coor, 3);
int e = enc.indexOf(coor);
floor[i - 2][j] = e == -1 ? 3 : e;
}
}
Upvotes: 0
Reputation: 59104
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.
Upvotes: 4