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

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

问题描述

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

这是code的一个项目我做了编程课程一大块。我遇到的问题是,声明布尔停止,并试图随机生成的布尔值分配给它后,我不能用它在if语句,以确定我是否应该追加更多个Y向的StringBuffer与否。我有一个构造内的随机发生器,以便部分是没有问题的。我认为自从我宣布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) should be if(stop == true), or simply (better!) if(stop).

这其实是一个很好的机会,明白了一个道理,为什么总是用如果(东西)如果你想看看它的真实而不是写如果(东西==真)(不良作风!)。

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!).

这样做停止=真,那么你指定真正停止,而不是比较。

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

那么,为什么code以下执行如果语句?

So why the code below the if statement executed?

查看 JLS - 15.26。赋值运算符的:

在运行时,分配前pression的结果是值
  在转让之后的变量已经发生。的结果
  转让前pression本身不是一个变量。

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.

所以,因为你写停止=真,那么你就满足了如果的条件。

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

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

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