如何在 if 语句中使用这个布尔值? [英] How to use this boolean in an if statement?

查看:28
本文介绍了如何在 if 语句中使用这个布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private String getWhoozitYs(){
    StringBuffer sb = new StringBuffer();
    boolean stop = generator.nextBoolean();
    if(stop = true)
    {
        sb.append("y");
        getWhoozitYs();
    }
    return sb.toString();
}

这是我在编程课程中做的一个项目的一段代码.我遇到的问题是,在声明布尔停止并尝试为其分配随机生成的布尔值之后,我无法在 if 语句中使用它来确定是否应该将更多 y 附加到 StringBuffer 中.我的构造函数中有 Random 生成器,所以这部分不是问题.我假设因为我在 if 语句之外声明了布尔值,所以我可以在内部使用它,但事实并非如此.真正的问题是如何在 if 语句中使用随机确定的布尔值.

This is a chunk of code for a project I'm doing in a programming course. The problem I'm having is that after declaring the boolean stop and trying to assign a randomly generated boolean value to it, I can't use it in the if statement to determine if I should append more y's to the StringBuffer or not. I do have the Random generator inside a constructor, so that part isn't a problem. I assumed that since I declared the boolean outside the if statement I would be able to use it inside, but that doesn't seem to be the case. The real question is how can I use a randomly determined boolean in an if statement.

推荐答案

if(stop = true) 应该是 if(stop == true),或者干脆 (更好!) if(stop).

if(stop = true) should be if(stop == true), or simply (better!) if(stop).

这实际上是一个很好的机会来看看为什么总是使用 if(something) 如果你想看看它是否是 true 而不是写 if(something == true)(风格不好!).

This is actually a good opportunity to see a reason to why always use if(something) if you want to see if it's true instead of writing if(something == true) (bad style!).

通过执行 stop = true 那么您将 true 分配给 stop 而不是比较.

By doing stop = true then you are assigning true to stop and not comparing.

那么为什么if语句下面的代码被执行了?

So why the code below the if statement executed?

请参阅 JLS - 15.26.赋值运算符:

在运行时,赋值表达式的结果是赋值发生后的变量.一个结果赋值表达式本身不是一个变量.

At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

所以因为你写了 stop = true,那么你就满足了 if 条件.

So because you wrote stop = true, then you're satisfying the if condition.

这篇关于如何在 if 语句中使用这个布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆