三元运算符中的多个条件 [英] Multiple conditions in ternary operators
本文介绍了三元运算符中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先,问题是编写一个Java程序,使用三元运算符找到三个最小的数字。
First off, the question is "Write a Java program to find the smallest of three numbers using ternary operators."
这是我的代码:
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.");
}
}
我试图在三元运算符中使用多个条件但是这不起作用。几天我不在,所以我不确定该做什么,老师的电话已经关闭了。有什么帮助吗?
I tried to use multiple conditions in the ternary operator but that doesn't work. I was absent a few days so I'm not really sure what to do and my teacher's phone is off. Any help?
推荐答案
试试
int min = x < y ? (x < z ? x : z) : (y < z ? y : z);
您还可以删除括号:
int min = x < y ? x < z ? x : z : y < z ? y : z;
这篇关于三元运算符中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文