简体   繁体   English

为什么布尔表达式的值不改变? (JAVA)

[英]Why doesn't the value of the boolean expression change? (Java)

The following is the code that I'm asking about: 以下是我要询问的代码:

int price = 0;
boolean isFree = (price == 0);

if (isFree) {
     price = 10;
     if (isFree)
         System.out.println("one");
     else
         System.out.println("two");
}

So I just wanna know why the isFree variable remains true while the price variable changes to 10. In other words why does the price variable switch to 10 without affecting the boolean expression? 因此,我只想知道为什么当价格变量更改为10时isFree变量仍然为true。换句话说,为什么价格变量切换为10而又不影响布尔表达式?

After initialized by boolean isFree = (price == 0); boolean isFree = (price == 0);初始化后, boolean isFree = (price == 0); , the isFree variable is determined to be true . isFree变量确定为true

it will not be changed even though the price is changed, unless you change it explicitly(like calling boolean isFree = (price == 0); again). 即使price已更改,它也不会更改,除非您明确更改它(例如再次调用boolean isFree = (price == 0); )。

Because the isFree variable had its value set once when you defined it. 因为在定义isFree变量后才对其值进行一次设置。 If you want the isFree variable to have another value, you need to set it. 如果希望isFree变量具有另一个值,则需要对其进行设置。

You could change your definition of isFree into a method: 您可以将isFree的定义更改为方法:

private boolean isFree(int price) {
    return price == 0;
}

Then any time you want to know if the price is free, you can call the isFree method: 然后,只要您想知道价格是否免费,都可以调用isFree方法:

int price = 0;

if (isFree(price)) {

    price = 10;

    if (isFree(price))
        System.out.println("one");
    else
        System.out.println("two");
}

It stays the same because you don't check the boolean variable again after comparing it the first time. 它保持不变,因为您在第一次比较布尔变量后就不再对其进行检查。 If you had another 如果你还有另一个

isFree = (price == 0);

after checking and re-assigning price to 10, then it would be false. 在检查价格并将价格重新分配给10之后,那将是错误的。

By using two isFree statements you are basically cancelling out the condition thus making it true (static) and not checking the new condition which is dynamic. 通过使用两个isFree语句,您基本上是在取消条件,从而使其变为true(静态),而不检查动态的新条件。

int price = 0;

boolean isFree = (price == 0);

if (isFree){
 price = 10;
 System.out.println("one");
}
else{
 System.out.println("two");
}

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

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