简体   繁体   English

返回语句中的Java逻辑运算符

[英]Java logical operators in return statements

So I'm working my way through some of the questions on codingbat.com to solidify some of the things I've learned so far, and es expected there's some questions where the provided answer is different than how I solved the problem. 因此,我正在努力解决codingbat.com上的一些问题,以巩固到目前为止我已经学到的一些知识,并期望有些问题所提供的答案与我解决问题的方式不同。 So for one question I used a style/format I saw in an answer for an earlier question and got it to work fine, but I just want some clarification on the logic. 因此,对于一个问题,我使用了在较早一个问题的答案中看到的样式/格式,并使其正常工作,但是我只想对逻辑进行一些说明。

Here is the question: 这是问题:

Given 2 int values, return true if they are both in the range 30..40 inclusive, or they are both in the range 40..50 inclusive. 给定2个int值,如果它们都在30..40(含)范围内,或者都在40..50(含)范围内,则返回true。

Here is my code: 这是我的代码:

public boolean in3050(int a, int b) {
  boolean in3040 = (a >= 30 && a <= 40) && (b >= 30 && b <= 40);
  boolean in4050 = (a >= 40 && a <= 50) && (b >= 40 && b <= 50);

  return in3040 || in4050;
}

So this answer worked, however I would like an expplanation on the return statement and exactly how the OR operator works with the two boolean variables. 所以这个答案行得通,但是我想对return语句进行一个解释,并希望OR运算符如何与两个布尔变量一起工作。 Also how would the statement work if there was an AND operator or a NOT before one of the variables. 如果变量之一之前有AND运算符或NOT,则该语句如何工作。

Thanks! 谢谢!

In Java a logical term is evaluated from left to right. 在Java中,逻辑术语是从左到右评估的。 This means: 这意味着:

  • for an OR-Statement: a || 对于OR语句:|| b --> if a is already true, then the whole term has to be true, b won't be evaluated, if a is false, b can still be true, in that case both variables would have been evaluated b->如果a已经为真,则整个项必须为true,b将不被求值;如果a为false,b仍然可以为真,在这种情况下,两个变量都将被求值
  • for an AND-Statement: a && b-> if a is already false, then same logic applies: the b variable doesn't need to be evaluated 对于AND语句:a && b->如果a已经为假,则适用相同的逻辑:b变量不需要求值

You can imagine rewriting your conditional operation as follows: 您可以想象重写条件操作,如下所示:

if (in3040) {
 return true;
}
if (in4050) {
 return true;
}

Considering the case of using the &&-Operator it would look like 考虑到使用&&-Operator的情况,它看起来像

if (!in3040) {
 return false;
}
if(!in4050) {
 return false;
}
return true;

这些运算符在return语句中的工作与程序中其他所有地方的工作完全相同。

Equivalency 等价

return [some expression] is equivalent to return ([some expression]) return [some expression]等于return ([some expression])

Thus, return in3040 || in4050; 因此, return in3040 || in4050; return in3040 || in4050; is equivalent to return ( in3040 || in4050 ); 等于return ( in3040 || in4050 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM