三元运算符中的多个条件

首先,问题是“编写一个Java程序,使用三元运算符找到三个最小的数字。”

这是我的代码:

class questionNine { public static void main(String args[]) { int x = 1, y = 2, z = 3; int smallestNum; smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y : (z<y && z<x) ? z; System.out.println(smallestNum + " is the smallest of the three numbers."); } } 

我尝试在三元运算符中使用多个条件,但这不起作用。 几天我不在,所以我不确定该做什么,老师的电话已经关闭了。 有帮助吗?

尝试

 int min = x < y ? (x < z ? x : z) : (y < z ? y : z); 

您也可以删除括号:

 int min = x < y ? x < z ? x : z : y < z ? y : z; 

由于这是家庭作业,我不仅会给你答案,而是一个算法,以便你可以自己解决。

首先研究如何使用单个三元运算符编写min(x,y)。

完成后,将min(x,y,z)的以下代码更改为使用三元运算符,然后在代码中替换上一步中计算出的min(x,y)。

 int min(x, y, z) { if (x <= y) { return min(x, z); } else { return min(y, z); } } 

当你真的不需要时,你正在测试z。 您的三元运算符必须是cond? ifTrue:ifFalse;

所以,如果你有多个条件,你有这个:

COND1? ifTrue1:cond2? 如果True2:ifFalse2;

如果您理解这一点,请不要在下面看。 如果您仍需要帮助,请查看以下内容。

我还包括一个没有嵌套的版本更清晰(假设你不需要嵌套它们。我肯定希望你的作业不需要你嵌套它们,因为那很丑!)

这是我想出的:

 class QuestionNine { public static void main(String args[]) { smallest(1,2,3); smallest(4,3,2); smallest(1,1,1); smallest(5,4,5); smallest(0,0,1); } public static void smallest(int x, int y, int z) { // bugfix, thanks Mark! //int smallestNum = (x 
 public static int min(int x, int y, int z) { return x 

我的解决方案

 public static void main(String args[]) { int x = 1, y = 2, z = 3; int smallestNum = (x < y && x < z) ? x : (y < x && y < z) ? y : (z < y && z < x) ? z:y; System.out.println(smallestNum + " is the smallest of the three numbers."); } 

我知道现在已经很晚了。 仅供参考,这也有效:

 int smallestNum = (x 

我的贡献 …

 public static int getSmallestNumber( int x, int y, int z) { return x < y && x < z ? x : y < x && y < z ? y : z; } public static void main ( String ... args ) { System.out.println( getSmallestNumber( 123, 234, 345 ) ); } 

最后一部分: (z (z缺少':':

 (z 
 int min = (x 

最好的方法是使用if和else语句创建一个示例,然后在其上应用三元运算符(q

这个答案迟了七年,所以我只给你代码:

 int smallestNumber = (x > y) ? ((y > z) ? z : y) : ((x > z) ? z : x); 

缩进应该解释代码,它只是在初始条件x > y上评估其他三元的三元组; / *如果该条件为真,则评估第一个三元组,否则评估第二个三元组。 * /