[英]Is it possible to have multiple conditions in a conditional statement?
我在互联网上搜索了这个答案,但找不到。 假设我有条件语句: totalRooms += bathrooms > 0 ? bathrooms : totalRooms;
totalRooms += bathrooms > 0 ? bathrooms : totalRooms;
但我想有两个或三个条件来检查它们是否为真,或者如果我想为条件使用类似“或”运算符的东西。 这可能与 Java 条件语句有关吗?
是的。 例如,测试浴室是否介于1
和99
之间,例如
totalRooms += bathrooms > 0 && bathrooms < 100 ? bathrooms : totalRooms;
一个 or 的写法相同,除了||
(短路)或|
(不是短路)。
例如,当然可以将多个条件与一系列条件运算符链接在一起
totalRooms += bathrooms > 0 ? bathrooms : bedrooms > 0 ? bedrooms : otherRooms;
但我真的不推荐它。 为了便于阅读,我将上面写成
if (bathrooms > 0) {
totalRooms += bathrooms;
} else if (bedrooms > 0) {
totalRooms += bedrooms;
} else {
totalRooms += otherRooms;
}
这是等效的。
另一种选择是使用&&
(and) 和||
(或)布尔表达式中的运算符,例如
totalRooms += (bathrooms > 0 || bedrooms > 0) ? (bathrooms + bedrooms) : otherRooms;
括号并不是必需的,但它们有助于提高可读性。
if(ConditionOne && ConditionTwo && ConditionThree)
{
// Code to execute
}
这是 Java 的一个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.