How to use this boolean expression 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 piece of code for a project that I am doing in a programming course. The problem I'm facing is that after declaring a logical stop and trying to assign it a randomly generated boolean, I cannot use it in an if statement to determine whether I add more y to the StringBuffer or not. I have a random number generator inside the constructor, so this part is not a problem. I suggested that since I declared a boolean outside the if statement, I could use it internally, but that doesn't seem to be the case. The real question is how can I use a random Boolean definition in an if statement.

+8
java if-statement boolean
source share
8 answers

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

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

By doing stop = true , you assign true to stop and do not compare.

So why is the code below the if executed?

See JLS - 15.26. Assignment Operators :

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

So, since you wrote stop = true , you satisfy the if condition.

+20
source share

Problem here

if (stop = true) is an assignment, not a comparison.

Try if (stop == true)

Also consider the ten bugs that Java programmers program .

+4
source share

In fact, the whole approach would be cleaner if you had to use only one instance of StringBuffer and not create it in all recursive calls ... I would go for:

 private String getWhoozitYs(){ StringBuffer sb = new StringBuffer(); while (generator.nextBoolean()) { sb.append("y"); } return sb.toString(); } 
+3
source share

Since stop is a boolean, you can change this part to:

 //... if(stop) // Or to: if (stop == true) { sb.append("y"); getWhoozitYs(); } return sb.toString(); //... 
+1
source share
 if(stop == true) 

or

 if(stop) 

= for destination.

== to check the condition.

 if(stop = true) 

It will assign true to stop and evaluate if (true). Therefore, it will always execute code internally, if because stop will always be assigned true.

+1
source share

Try the following: -

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

= for assignment

records

 if(stop){ //your code } 

or

 if(stop == true){ //your code } 
+1
source share

in addition you can just write

 if(stop) { sb.append("y"); getWhoozitYs(); } 
+1
source share

All Articles