Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use this boolean in an if statement?

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

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.

like image 615
user2041920 Avatar asked Mar 14 '13 15:03

user2041920


People also ask

Can you use == for Booleans?

Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".

Is it possible to write Boolean expressions in if condition?

if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed.

How do you use Booleans in an if statement in Python?

Use the is operator to check for a boolean value in an if statement, e.g. if variable is True: . The is operator will return True if the condition is met and False otherwise.


2 Answers

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.

So why the code below the if statement executed?

See the JLS - 15.26. Assignment Operators:

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.

like image 155
Maroun Avatar answered Oct 23 '22 00:10

Maroun


if(stop == true)

or

if(stop)

= is for assignment.

== is for checking condition.

if(stop = true) 

It will assign true to stop and evaluates if(true). So it will always execute the code inside if because stop will always being assigned with true.

like image 34
Achintya Jha Avatar answered Oct 22 '22 23:10

Achintya Jha