-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);
YCF_L
  • 51,266
  • 13
  • 85
  • 129
Aditya R.
  • 3
  • 3
  • By the way, the `char` type is obsolete, supplanted by Unicode code point integer numbers. – Basil Bourque Jun 11 '20 at 19:06
  • 1
    Possible duplicate of https://stackoverflow.com/q/35189762/642706 – Basil Bourque Jun 11 '20 at 19:08
  • 1
    Does this answer your question? [Do Ternary and If/Else compile to the same thing, why?](https://stackoverflow.com/questions/35189762/do-ternary-and-if-else-compile-to-the-same-thing-why) – LazyCoder Jun 12 '20 at 05:49

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);
YCF_L
  • 51,266
  • 13
  • 85
  • 129
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
  • 349
  • 2
  • 11