例如,
if (bool1 ^ bool2 ^ bool3 ^ bool4)
{
// Do whatever
}
它应该只在恰好满足其中一个条件时执行。
最佳答案
将 boolean 值作为整数相加并检查它们是否等于 1。
在无法将 boolean 值转换为整数的语言中,例如 Java,更冗长的选项是:
if ((bool1 ? 1 : 0) + (bool2 ? 1 : 0) + (bool3 ? 1 : 0) + (bool4 ? 1 : 0) == 1) {
// only runs when one of bool 1-4 is true
}
但是,在将 boolean 值转换为整数有效的其他语言中,您可以执行以下操作:
if ((int)(bool1) + (int)(bool2) + (int)(bool3) + (int)(bool4) == 1) {
// only runs when one of bool 1-4 is true
}
关于java - 是否可以使用 XOR 来检测多个条件中的一个是否为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460307/