Here is the ternary statement that I need help converting into an if/else statement:
char rightColor = necklace.charAt(i + 1 == necklace.length() ? 0 : i + 1);
Here is the ternary statement that I need help converting into an if/else statement:
char rightColor = necklace.charAt(i + 1 == necklace.length() ? 0 : i + 1);
There are many ways, it depends on your logic, here is one of the solution you can do:
int index;
if (i + 1 == necklace.length()) {
index = 0;
} else {
index = i + 1;
}
char rightColor = necklace.charAt(index);
The ternary operator is equivalent to asking:
Is i + 1
equal to necklace.length
?
true
, then the value 0
(at the left of :
) is passed to the charAt()
method.false
, then the value i + 1
is passed.So a verbose equivalent would be, for example:
char rightColor ;
if ( i + 1 == necklace.length() ) {
rightColor = necklace.charAt(0) ;
} else {
rightColor = necklace.charAt(i + 1) ;
}