Java 中的布尔表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/493233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:19:46  来源:igfitidea点击:

Boolean expressions in Java

javabooleanreturn

提问by user42155

I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.

我有一个关于 Java 中 return 语句中布尔变量的含义(评估)的问题。

I know that:

我知道:

if (var) { ... }

is the same as:

是相同的:

if (var==true) { ... }

In the second case we explicitly say var==true, but we don't need to do this, because Java evaluates var as true anyway. I hope I have understood this right.

在第二种情况下,我们明确地说 var==true,但我们不需要这样做,因为 Java 无论如何都会将 var 评估为 true。我希望我已经正确理解了这一点。

My question is: is it the same when Boolean variables are returned? When we have a return statement?

我的问题是:返回布尔变量时是否相同?当我们有一个 return 语句时?

For example, a task specifies: the method looksBetter() will return true only if b < a. My solution was:

例如,任务指定:仅当 b < a 时,方法 lookBetter() 才会返回 true。我的解决方案是:

public boolean looksBetter() {
     if (b < a) {
         return true;
     } else {
         return false;
     }
}

The simple answer was:

简单的答案是:

public boolean lookBetter() {
      return b < a;
}

So, it seems that here we have again this implicit assumption that in case b < a == true, the return of the method is true. I am sorry ... it seems very trivial, but I am somehow not comfortable with this, and I don't know why. Thank you.

因此,似乎在这里我们再次有一个隐含的假设,即在 b < a == true 的情况下,该方法的返回为 true。我很抱歉......这似乎很微不足道,但我不知何故对此感到不舒服,我不知道为什么。谢谢你。

回答by Rob Hruska

It's not an "implicit assumption," it's what the compiler's doing. The b < ais just an expression, the same as if it were used for an ifstatement. The expression evaluates to a boolean, which is then returned.

这不是“隐式假设”,而是编译器正在做的事情。Theb < a只是一个表达式,就好像它用于if语句一样。表达式的计算结果为 a boolean,然后返回。

Also noteworthy, you seem to interchange booleanand Booleanas though they're the same, but they're actually not. booleanis the primitiveform while Booleanis an Objectthat wraps a boolean.

同样值得注意的是,您似乎互换了booleanBoolean好像它们是相同的,但实际上并非如此。boolean原始形式,而Boolean是包装 a的对象boolean

回答by Bill Zeller

Yes, this is true for all booleans. You can think of if(expression) evaluating 'expression' to see if it's 'true' or 'false'. When you do

是的,这适用于所有布尔值。您可以考虑 if(expression) 评估 'expression' 以查看它是 'true' 还是 'false'。当你做

if(b < a == true)

it first tests to see if b < a and if it is, it now tests:

它首先测试是否 b < a,如果是,它现在测试:

if(true == true)

It now tests whether true == true (which it obviously does). Java isn't doing anything tricky when you leave out the extra '== true', it just needs to perform one fewer test. There's no reason you couldn't say:

它现在测试是否 true == true (它显然是这样做的)。当您省略额外的 '== true' 时,Java 不会做任何棘手的事情,它只需要少执行一项测试。没有理由你不能说:

if(((b < a == true) == true) == true)

but it would cause Java to perform an extra test each time it sees an equals sign.

但它会导致 Java 每次看到等号时执行额外的测试。

回答by Paul Tomblin

Don't needlessly complicate your code. If you feel the need to say "a < b == true", then you can follow that to its logical conflusion (conclusion + confusion) and say "((((((((...(a<b) == true) == true).... == true)"

不要不必要地使您的代码复杂化。如果你觉得有必要说“a < b == true”,那么你可以按照它的逻辑混淆(结论+混淆)说“ ((((((((...(a<b) == true) == true).... == true)

"a < b" is a boolean expression. If you already have a boolean, why compare it to another boolean? You're not making it moreboolean that way.

“a < b”是一个布尔表达式。如果您已经有一个布尔值,为什么要将它与另一个布尔值进行比较?你并没有让它变得更布尔。

回答by slf

Just like C++ every statement has a return value, even things on the left hand side of the operator. Some of the crazier C++ I've seen has operations on the left hand side with their results being assigned to.

就像 C++ 一样,每个语句都有一个返回值,即使是运算符左侧的内容。我见过的一些更疯狂的 C++ 在左侧进行了操作,并将结果分配给了它们。

I find it works better if I do the following:

如果我执行以下操作,我发现效果会更好:

bool result = (b > a);
return result;

The reason only being that is is a bit easier to debug (in just about any IDE). I find that I always wrap it in parenthesis, I'm not quite sure why. I think it keeps the variable electrons warm while they sleep at night.

唯一的原因是调试起来更容易一些(几乎在任何 IDE 中)。我发现我总是把它放在括号里,我不太确定为什么。我认为它使可变电子在晚上睡觉时保持温暖。

回答by Tai Squared

Your method will work, but it can be a bit unclear what exactly should happen, especially if you just have variables named a and b. You want to document the method and have variables with proper names.

您的方法会起作用,但可能有点不清楚究竟会发生什么,尤其是当您只有名为 a 和 b 的变量时。您想要记录方法并拥有具有正确名称的变量。

Also, if the code is confusing to you just after you wrote it, think of someone who will come in 6 months and won't have any idea what is going on. Proper documentation and comments will help greatly.

另外,如果代码刚写完就让你感到困惑,想想一个会在 6 个月后到来并且不知道发生了什么的人。适当的文档和评论将有很大帮助。

回答by David Thornley

A Java conditional requires a boolean value. If you can put it into an if statement, it's already a boolean, and requires no further fiddling if what you want is a boolean.

Java 条件需要一个布尔值。如果您可以将其放入 if 语句中,则它已经是一个布尔值,如果您想要的是一个布尔值,则无需进一步摆弄。

Indeed, constructs like value == truecan be tricky. I don't offhand remember the promotion rules in Java, but in C++ a bool can be promoted to an int, with false becoming 0 and true becoming 1. Therefore, int a = 2; if (a)and int a = 2; if (a == true)will do different things.

事实上,像这样的构造value == true可能很棘手。我不记得随便在Java中的促销规则,但在C ++一个布尔值可以提升为int,使用假成为0和真正成为1.因此,int a = 2; if (a)int a = 2; if (a == true)会做不同的事情。

回答by Bill K

I think you are asking about why you are having a conceptual problem with it.

我想你是在问为什么你会遇到概念上的问题。

I think the basic problem is that when you directly return a boolean value, you are missing something, and you are. It's the method name in your case.

我认为基本的问题是,当您直接返回一个布尔值时,您会遗漏一些东西,而您确实是。在您的情况下,这是方法名称。

Your LooksBetter means nothing. What you are really thinking is this:

你的 LooksBetter 毫无意义。你真正的想法是这样的:

boolean isEarlier(Time a, Time b) {
    if(a < b) //for simplicity let's ignore that this won't work.
        return true;
    else
        return false;
}

Now, you can reduce that to:

现在,您可以将其减少为:

boolean isEarlier=a < b;

Hmm, well now we can see that a is earlier than b, and that's what the intermediate value isEarlier means.

嗯,现在我们可以看到 a 早于 b,这就是中间值 isEarlier 的意思。

So once you kind of internalize that intermediate value, this makes more sense:

所以一旦你把这个中间值内化了,这就更有意义了:

boolean isEarlier(Time a, Time b) {
    return a < b;
}

You have to think of that "Boolean" as a real value, not just some intermediate state. If it makes you uncomfortable, feel free to make it a variable (it really doesn't cost anything, and may make it more readable for you right now).

您必须将“布尔值”视为一个真实值,而不仅仅是一些中间状态。如果它让您感到不舒服,请随意将其设置为变量(它确实不需要任何费用,并且现在可能会使您更容易阅读)。

Later you'll look back on your code and be more comfortable with the shorter way of looking at it. It mostly takes time for your mind to grow some new paths, don't be embarrassed to be explicit in the meantime.

稍后,您将回顾您的代码,并以更短的方式查看它。你的头脑通常需要时间来发展一些新的路径,在此期间不要不好意思直言不讳。

回答by Emil Fors

Your confusion might be eased if you try thinking about operators as methods. Using your example, you had the < "less than" operator. For our purposes, the < operator can really be considered a "method" (it only doesn't look like one), which takes two parameters and returns a boolean result. If the "method" were named lessThan, your example would be equivalent to this:

如果您尝试将运算符视为方法,则可能会减轻您的困惑。使用您的示例,您有 <“小于”运算符。就我们的目的而言,< 运算符实际上可以被视为一种“方法”(它只是看起来不像一个),它接受两个参数并返回一个布尔结果。如果“方法”被命名为lessThan,则您的示例将等效于:

public boolean lookBetter() {     
  return lessThan(b, a);     
} 

Perhaps seeing it like that makes it a tad easier to understand? Incidentally, when I was leading exercise groups in the 'Programming 101' course back in Uni, this proved to be by far the hardest thing to teach, and a lot of people had trouble grasping the concepts involved. It almost seemed to be akin to learning to ride a bike or to swim, once you get how it works it becomes self-evident in a way.

也许这样看会让它更容易理解?顺便说一下,当我在 Uni 的“Programming 101”课程中领导练习小组时,事实证明这是迄今为止最难教的事情,而且很多人都难以掌握所涉及的概念。这几乎就像学习骑自行车或游泳一样,一旦你了解它是如何工作的,它就会在某种程度上变得不言而喻。