-2

So I'm converting a bool to a int then to a char using branch-less programming. But when ran I'm getting an empty print out. I'm converting it so if a bool is False it generates an O but if True and X.

int Turn = (boolturn) ? 1:0 * 9 + 79;
char playerchr = (char)Turn;
System.out.println(playerchr);
3
  • How do you convert from boolean to int? Aug 8, 2020 at 7:50
  • Wups the code snippet was formated wrong Aug 8, 2020 at 7:51
  • Since you have to use a conditional anyway, why not just convert to char directly, using char literals? Why should someone who reads your code have to think about what is special about the numbers 79 and 9? Hint: the person who reads your code most often is you. Aug 8, 2020 at 7:56

2 Answers 2

1

Use brackets where they're needed: int Turn = (boolturn ? 1 : 0) * 9 + 79;


Also, why not just char playerchr = boolturn ? 'X' : 'O' (piggybacking on @StephenC's answer)? It's not less "branchless" than the former variant (the ternary operator ?: is still a kind of branching, though).

0

As Andrew Vershin spotted, you made a mistake with the operator precedence. The * operator has a higher precedence than the conditional operator, so you need to use parentheses to express what you are apparently trying to do here.


But seriously, the sane way to write that code in Java is:

char playerchr = (boolturn) ? 'O' : 'X';

And note that should be turn not Turn, and boolTurn not boolturn, and playerChar not playerchr.

Java code should be written to be readable ... if you want other people to be able to read it. (Or even if you want to be able to read it yourself in a few weeks time!)

Not the answer you're looking for? Browse other questions tagged or ask your own question.