简体   繁体   English

如何在super关键字内使用具有多个条件的三元运算符?

[英]How to use a ternary operator with multiple conditions inside of the super keyword?

I am trying to turn the below code into one line of code using the super constructor and the ternary operator. 我正在尝试使用超级构造函数和三元运算符将以下代码转换为一行代码。 Have tried multiple things but nothing is working. 已经尝试了多种方法,但是没有任何效果。

if (c == 0) {
    super(Piece.JMAN, x, y, Color.red);
} else if (c == 1) {
    super(Piece.JMAN, x, y, Color.green);
} else {
    super(Piece.JMAN, x, y, Color.yellow);
}

As @jacobg wrote in the comments, you can do 正如@jacobg在评论中所写,您可以执行

super(Piece.JMAN, x, y, c == 0 ? Color.red : c == 1 ? Color.green : Color.yellow)

For purposes of readability, you might want to split it into two statements with added parentheses. 出于可读性考虑,您可能希望将其拆分为两个带有括号的语句。

Color color = (c == 0 ? Color.red : (c == 1 ? Color.green : Color.yellow));
super(Piece.JMAN, x, y, color);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM