-6

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);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Aditya R.
  • 1
  • 4

2 Answers2

2

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);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

The ternary operator is equivalent to asking:

Is i + 1 equal to necklace.length?

  • If true, then the value 0 (at the left of :) is passed to the charAt() method.
  • If 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) ;
}
Mario MG
  • 364
  • 2
  • 13