三元运算符中的多个条件
首先,问题是“编写一个 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.");
}
}
我尝试在三元运算符中使用多个条件,但这不起作用。我缺席了几天,所以我真的不知道该怎么办,而且我老师的电话也关机了。有什么帮助吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
尝试
也可以删除括号:
Try
You can also remove the parenthesis:
由于这是家庭作业,我不仅会给您答案,还会提供一个算法,以便您可以自己解决。
首先弄清楚如何使用单个三元运算符编写 min(x, y)。
完成后,将 min(x, y, z) 的以下代码更改为使用三元运算符,然后替换您在上一步中计算出的 min(x, y) 的代码。
Since this is homework I'm not just going to give you the answer, but instead an algorithm so that you can work it out yourself.
First work out how to write min(x, y) using a single ternary operator.
Once you have that, change the following code for min(x, y, z) to use a ternary operator then substitute in the code for min(x, y) that you worked out from the previous step.
当您确实不需要时,您正在测试 z。您的三元运算符必须采用 cond 形式?如果真:如果假;
所以如果你有多个条件,你有这个:
cond1? ifTrue1:条件2?如果为真2:如果为假2;
如果你明白这一点,就不要看下面了。如果您仍然需要帮助,请查看下文。
我还提供了一个更清晰的不嵌套它们的版本(假设您不需要嵌套它们。我当然希望您的作业不需要您嵌套它们,因为那非常丑陋!)
。
。
这是我的想法:
You're testing for z, when you really don't need to. Your ternary operator must be of form cond ? ifTrue : ifFalse;
so if you have multiple conditions, you have this:
cond1? ifTrue1 : cond2? if True2 : ifFalse2;
If you understand this, don't look below. If you still need help, look below.
I also included a version that doesn't nest them that is clearer (assuming you don't need to have them nested. I sure would hope your assignment doesn't require you to nest them because that's pretty ugly!)
.
.
Here's what I come up with:
我知道已经晚了。仅供参考,这也有效:
I know it's late. Just for information this also works:
最后一部分:
(z 缺少 ':' :
The last part:
(z<y && z<x) ? z
is missing a ':' :我的解决方案:
My solution:
我的贡献...
My contribution ...
这个答案迟到了七年,所以我只给你代码:
缩进应该解释代码,它只是一个三元数,它在初始条件
x > > 上评估其他三元数。 y
; /* 如果条件为真,则评估第一个三元数,否则评估第二个三元数。 */This answer is coming in seven years late, so I'll just give you the code:
The indentation should explain the code, which is simply a ternary that evaluates other ternaries on the initial condition
x > y
; /* the first ternary gets evaluated if that condition is true, else the second one gets evaluated. */你错过了 z var 之后的值
最小数 = (x
you missed the value after z var
smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y : (z<y && z<x) ? z:0;
Try this, it works
最好的方法是使用 if 和 else 语句创建一个示例,然后对其应用三元运算符
(q
best way to do this is to make an example using if and else statement and then apply the ternary operators on it
(q