简体   繁体   English

布尔真或假

[英]Boolean True or False

public class Main {
    public static void main(String[] args) {
        boolean b = false;
        b = true;

        boolean toBe = false;
        b = toBe || !toBe;
        if (b) {
            System.out.println(toBe);
        }



    }

I saw this code online while trying to learn boolean and the output of this is false.我在尝试学习布尔值时在网上看到了这段代码,结果是错误的。 Can someone please explain to me how why is the output false?有人可以向我解释为什么输出是假的吗? Thank you谢谢

You set "b" to false and then changed it to true, so "b" is true.您将 "b" 设置为 false,然后将其更改为 true,因此 "b" 为 true。 Then you set "toBe" to false.然后将“toBe”设置为false。 The next line does nothing, it returns true but doesn't assign it to anything.下一行什么都不做,它返回 true 但不将它分配给任何东西。 Then you check if "b" equals true, and it does.然后你检查“b”是否等于真,它确实如此。 So then you print out "toBe" which equals false.那么你打印出“toBe”,它等于false。 That is why false is printed.这就是为什么打印 false 的原因。

Hope this helps!!希望这可以帮助!!

|| is the logical or operator.是逻辑或运算符。 It returns true if at least one operator is true.如果至少一个运算符为真,则返回真。 It's truth table looks like this:它的真值表如下所示:

a b a || b
1 1   1
1 0   1
0 1   1
0 0   0

Which means that b will be true, and thus the block within the if statement will execute.这意味着 b 将为真,因此 if 语句中的块将执行。 And it outputs "false" since that's the value of toBe .它输出“false”,因为这是toBe的值。

since boolean toBe = false;因为boolean toBe = false;

b=toBe || !toBe 
b = false || !fasle
b = false || true 
b = true

so b is true which means所以 b 是真的,这意味着

System.out.println(toBe); // prints false since tobBE is false

PLEASE: see truth table for short circuit logical or ||请:短路逻辑或||请参见真值表

True || x = True
false || True = True
false || Flase = false

x -> is a don't care ie either true or false x ->是一个不在乎,即truefalse

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

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