为什么将布尔转换为字符时得到空值或空字符打印?

huangapple go评论66阅读模式
英文:

Why am I getting a empty or null print when converting bool to char

问题

所以我正在使用无分支编程将布尔值转换为整数,然后转换为字符。但是当运行时,我得到一个空白的输出。我将它转换为如果布尔值为False,则生成一个'O',但如果为True,则生成'X'。

int Turn = (boolturn) ? 1 : 0 * 9 + 79;
char playerchr = (char) Turn;
System.out.println(playerchr);
英文:

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);

答案1

得分: 1

使用括号在需要的地方:int Turn = (boolturn ? 1 : 0) * 9 + 79;


另外,为什么不使用 `char playerchr = boolturn ? 'X' : 'O'`(借鉴自 @StephenC 的答案)?它并不比前一种变体更少“分支”(三元运算符 `?:` 仍然是一种分支,尽管如此)。

英文:

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

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

答案2

得分: 0

如Andrew Vershin所指出,您在运算符优先级方面犯了一个错误。*运算符的优先级高于条件运算符,所以您需要使用括号来表达您显然想要做的事情。

但说真的,在Java中编写这段代码的明智方式是:

char playerChar = (boolTurn) ? 'O' : 'X';

请注意应该是turn而不是TurnboolTurn而不是boolturn,以及playerChar而不是playerchr

Java代码应该被编写得易读...如果您希望其他人能够阅读它的话。甚至如果您希望在几周后自己能够阅读它的话!

英文:

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) ? &#39;O&#39; : &#39;X&#39;;

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!)

huangapple
  • 本文由 发表于 2020年8月8日 15:48:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63313004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定