使用 java 运算符(XOR 和 AND/OR)
在程序中,我试图检查两个布尔值(从函数返回);需要检查的条件是:
-只有当返回值中的任何一个为 true 而另一个为 false 时,我才会遇到问题;
-否则,如果两者都是真或假,我很高兴进入下一步。
以下两个示例中哪一个是检查条件的有效方法,或者是否有更好的解决方案?
a 和 b 是整数值,我正在检查 isCorrect
函数中的正确性条件,它返回 true 或 false。
1.2
// checking for the correctness of both a and b
if ((isCorrect(a) && !isCorrect(b)) ||
(!isCorrect(a) && isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are both correct or incorrect
}
.
// checking for the correctness of both a and b
if (! (isCorrect(a) ^ isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are correct or incorrect
}
谢谢,
Ivar
P.S:代码可读性不是问题。 编辑:我的意思是在第二个选项中有一个异或。 另外,我同意 == 和 != 选项,但是如果我必须使用布尔运算符怎么办?
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:
- only if any one of the returned value is true and the other is false then I have a problem;
- else if both are true or false I am good to go to next step.
Which of the following two examples would be the efficient way to check the condition, or is there a better solution?
a and b are integer values on which I am checking a condition for correctness in isCorrect
function and it return true or false.
1.
// checking for the correctness of both a and b
if ((isCorrect(a) && !isCorrect(b)) ||
(!isCorrect(a) && isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are both correct or incorrect
}
2.
// checking for the correctness of both a and b
if (! (isCorrect(a) ^ isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are correct or incorrect
}
Thanks,
Ivar
P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的测试不需要布尔运算符,只需这样:
编辑 - 我故意不使用相同的注释来反映注释的主要目的应该是描述意图,而不是具体的实现。在这种情况下,最简单的意图声明是
a
和b
获得相同的结果。Your test doesn't need boolean operators, just this:
EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation. In this case the simplest statement of intent is that both
a
andb
obtained the same result.简单地:
simply:
这个怎么样?
您也可以使用 XOR,但是 != 工作正常,并且如果您处理布尔值,则更具可读性,IMO。
How about this?
You can use XOR also, but != works fine and is more readable if you are dealing with boolean values, IMO.